读书人

请大家帮小弟我看看这个程序为什么会

发布时间: 2012-03-31 13:13:26 作者: rapoo

请大家帮我看看这个程序,为什么会事段错误?
#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;} 

读书人网 >C语言

热点推荐