首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

请大家帮小弟我看看这个程序,为什么会事段异常

2012-03-31 
请大家帮我看看这个程序,为什么会事段错误?#includestdio.h#includestdlib.hint main(void){FILE *fp

请大家帮我看看这个程序,为什么会事段错误?
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
FILE *fp;
int ch;
char filename[41];
long count=0;
printf("Input the name of file:");
scanf("%s",filename);
if(fopen(filename,"r")==NULL)
{
printf("Can't open the %s",filename);
exit(1);
}
while((ch=getc(fp))!=EOF)
{
putc(ch,stdout);
count++;

}
fclose(fp);
printf ("\nFile %s has %ld characters\n",filename,count);
return 0;

}
$ gcc program_chap13-1.c -o chap13-1 
$ ./chap13-1 
Input the name of file:file
段错误




[解决办法]
你fp没有初始化阿是NULL

C/C++ code
if ((fp=fopen(filename,"r"))==NULL)
[解决办法]
C/C++ code
#include<stdio.h>#include<stdlib.h>int main(void){    FILE *fp;    int ch;    char filename[41];    long count=0;    printf("Input the name of file:");    scanf("%s",filename);    if ((fp=fopen(filename,"r"))==NULL)    {        printf("Can't open the %s",filename);        exit(1);    }    while((ch=getc(fp))!=EOF)    {        putc(ch,stdout);        count++;    }    fclose(fp);    printf ("\nFile %s has %ld characters\n",filename,count);    return 0;} 

热点排行