使用c计算文件中的行数

标签 c pointers casting segmentation-fault

我正在尝试创建一个 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计算文件中的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35433338/

相关文章:

c - 这个涉及后增量运算符的表达式是如何求值的?

string - 如何在字符串指针中找到子字符串

c - 在二维矩阵的上下文中 C 中 ** 和 &** 之间的区别

java - 将 List<SubClass> 转换为 List<BaseClass> 的最有效方法

c - Linux 上的 GetTcpTable 等效项

C:数组结构中的结构数组

c++ - 将 namespace 添加到具有 C header 的 C++ 实现

c++ - 如何在不使用全局变量的情况下在函数之间使用多个变量?

java - 将对象转换为数组 - IllegalArgumentException - 参数不是数组

用于后期绑定(bind)错误的 C++ dynamic_cast - 切片