通过终端写入文件名时出现分段错误

问题描述 投票:0回答:1

我已经研究这个问题有一段时间了,但无法弄清楚。 我有以下代码和一个包含 10 个数据点的 test.txt 文件:

int main(){
//opening file for reading ("r").
    char *filename;
    printf("Please enter file name: ");
    scanf("%s", filename);
    FILE *file = fopen(filename,"r");


//Counting total number of data points
    int ch; //store character reading
    while(!feof(file)){
      ch = fgetc(file);
      if(ch == '\n'){
        count++;
      }
    }
      fclose(file);
    printf("it is done \n");
    printf("%i", count);

如果我直接使用文件名对其进行编码,它就会工作并成功计算 10 个数据点。但是,每当我尝试将其设置为扫描文件名时,一旦我在终端上运行它并收到消息“请输入文件名”,我就会将其写入,但最终总是会得到“分段错误”。我做错了什么,请帮忙。

c string file scanf
1个回答
0
投票

看起来您正在尝试计算文本文件中的行数。但是,您的代码存在一些问题。首先,您没有声明

count
变量,该变量应该保存行数。其次,在使用
filename
读取文件名之前,需要为
scanf
指针分配内存。

这是代码的修改版本:

include <stdio.h>

int main() {
    char filename[100]; // Allocate memory for the filename
    int count = 0; // Initialize count to zero

    printf("Please enter file name: ");
    scanf("%s", filename);

    FILE *file = fopen(filename, "r");

    if (file == NULL) {
        printf("Unable to open the file.\n");
        return 1; // Exit with an error code
    }

    int ch; // Store character reading
    while ((ch = fgetc(file)) != EOF) {
        if (ch == '\n') {
            count++;
        }
    }

    fclose(file);
    printf("Number of lines in the file: %d\n", count);

    return 0; // Exit with success code
}
```

在此代码中:

  1. 我已经声明了
    filename
    具有固定大小来存储文件名。
  2. 我添加了错误检查以确保文件可以成功打开。
  3. 我已将
    count
    初始化为零。
  4. 我修改了
    while
    循环来读取字符直到文件末尾 (
    EOF
    )。

此代码应正确计算指定文本文件中的行数。确保包含错误处理以处理文件可能不存在或无法打开的情况。

© www.soinside.com 2019 - 2024. All rights reserved.