我试图创建一个C程序来计算文件中的行数。 但它会抛出错误,如下所示。
请检查并告诉我出错的地方
#include <stdio.h>
#include <stdlib.h>
int counter(char *file_name);
int counter(char *file_name){
char ch;
FILE *fp;
int l=0;
fp = fopen(file_name,"r");
while( ( ch = fgetc(fp) ) != EOF )
{
if ((ch) == '\n')
{
l=l+1;
}
}
printf("hi there \n");
fclose(fp);
return l;
}
int main() {
char file_n,*file_name;
int result;
printf("Enter File Name: ");
scanf("%s",&file_n);
file_name=file_n;
result=counter(file_name);
printf("%d",result);
printf("%s\n",&file_n);
return 0;
}
PFB执行代码:
subbi@subbi-VirtualBox:~/Desktop$ ls
bar.txt DWA calssification.py myp.c prj1 tes.c test.c test.py tikinter tkinter_actual Untitled Document wctester
subbi@subbi-VirtualBox:~/Desktop$ gcc myp.c
myp.c: In function ‘main’:
myp.c:30:14: warning: assignment makes pointer from integer without a cast [enabled by default]
file_name=file_n;
^
subbi@subbi-VirtualBox:~/Desktop$ ./a.out
Enter File Name: bar.txt
Segmentation fault (core dumped)
subbi@subbi-VirtualBox:~/Desktop$
答案 0 :(得分:4)
ch
必须属于int
类型;
while( ( ch = fgetc(fp) ) != EOF ) // fails if ch is of type char