【问题标题】:Segmentation fault while reading a file in C在 C 中读取文件时出现分段错误
【发布时间】:2019-03-27 01:13:12
【问题描述】:

晚上好!我现在的目标是做一些小的东西来读出任何类型文件中的字符(并将它们放入一个字符串中以供程序稍后使用)但我目前一直遇到一个问题,当我运行代码和它时“input[n] = (char)c;”行的分段错误并且我尝试通过打印字符和 n 的值来进行故障排除,并且每次(尽管我将 malloc 更改为不同的大小)printf 语句都会在数字“134510”的一半处打印,或者会在之前的偏移量 134509 处打印字符故障在下面的行。我想知道我的问题是什么以及如何解决它,因为我很奇怪该程序只能通过大约 10% 的文件。

谢谢!!

int c = 0; //Counting the current character being read
int n = 0; //Counting the current character being written

char *input; //A string of all characters in the file

FILE *inputFile; //File to read

if(!(inputFile = fopen(argv[1],"r"))){  // Open in read mode
    printf("Could not open file");   // Print and exit if file open error
    return 1;
}

input = (char *)malloc(sizeof(inputFile) * sizeof(char));

while (1){  //Put all of the characters from the file into the string
    c = fgetc(inputFile);

    if(feof(inputFile)){ //If it reaches the end of the file, break the loop
        break;
    }

    printf("%c ", c); //Troubleshooting

    input[n] = (char)c;
    n++;
}

【问题讨论】:

    标签: c string segmentation-fault


    【解决方案1】:

    问题是sizeof(inputFile) 没有返回文件的大小。它返回FILE* 指针的大小(以字节为单位);该指针的大小与底层文件的大小完全无关。

    How do you determine the size of a file in C? 讨论了您要查找的内容

    【讨论】:

      【解决方案2】:

      你出现段错误的原因是因为这行:

      input = (char *)malloc(sizeof(inputFile) * sizeof(char));
      

      malloc 文件的大小可能看起来不错;但是,您得到的是 inputFile POINTER 的大小。这与普通文件完全不同,因为指针在大多数计算机上只有 4 个字节!

      这意味着您只分配了 4 个字节的数据。

      如何避免这种情况?

      由于您只是尝试读取字符,因此您可以:

      while ((int)(result = getline(&line, &capacity, inputs)) != -1)
      

      这将读取整行,您可以将该行放入另一个字符 *。

      【讨论】:

        【解决方案3】:

        您不必事先知道文件大小。

        您可以使用下面介绍的方法:

        1. 打开文件
        2. 分配结果缓冲区
        3. 读取字符
        4. 如果 EOF 然后关闭文件,追加零字节并返回缓冲区。
        5. 将字符附加到缓冲区
        6. 如果缓冲区末尾重新分配双倍缓冲区大小。
        7. 从 3 继续

        【讨论】:

          猜你喜欢
          • 2022-10-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-06-08
          • 1970-01-01
          • 2014-05-02
          • 2020-08-14
          相关资源
          最近更新 更多