请大家帮我看看这个程序,为什么会事段错误?
#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
if ((fp=fopen(filename,"r"))==NULL)
[解决办法]
#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;}