【问题标题】:calculate number of lines in file using c使用c计算文件中的行数
【发布时间】:2016-02-16 13:01:00
【问题描述】:

我正在尝试创建一个 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$ 

【问题讨论】:

  • 您正在使用带有 %s 的 scanf 来解析字符串,但将其分配给单个 char 变量。
  • 是的。 'char file_n,*file_name;'一个是指针,另一个不是,所以'file_name=file_n;'是类型不匹配。
  • 如果您将file_n 更改为足够大的数组,例如char file_n[200],它可能会起作用(但不会避免缓冲区溢出。
  • 您还应该将变量char ch 更改为int ch,因为常量EOF 不一定可以用char 表示。
  • @Ian Abbott:或者更好的是像“%199s”(使用 char file_n[200])。然后没有缓冲区溢出。

标签: c pointers casting segmentation-fault


【解决方案1】:

ch 必须int类型;

while( ( ch = fgetc(fp) ) != EOF ) // fails if ch is of type char

fgetc() description in (a draft of) the C11 Standard

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-05
    相关资源
    最近更新 更多