我正在尝试创建一个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$
最佳答案
ch
必须是int
类型;
while( ( ch = fgetc(fp) ) != EOF ) // fails if ch is of type char
请参见
fgetc()
description in (a draft of) the C11 Standard。关于c - 使用c计算文件中的行数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35433338/