首页 > 解决方案 > fopen 给我一个分段错误

问题描述

我正在尝试打开 output_voice_capture.txt 但它给了我一个分段错误,不仅文件存在而且它具有读取权限。

#include <stdio.h>
#include <stdlib.h>


int main()
{
    FILE * fPtr;

    char ch;


    /* 
     * Open file in r (read) mode. 
     */
     printf("Opening file ......\n");
     fPtr = fopen("/flash/etc/output_voice_capture.txt", "r");


    if(fPtr == NULL)
    {
        /* Unable to open file hence exit */
        printf("Unable to open file.\n");
        printf("Please check whether file exists and you have read privilege.\n");
        exit(EXIT_FAILURE);
    }


    /* File open success message */
    printf("File opened successfully. Reading file contents character by character.\n");

    do 
    {    printf("Read single character from file ......\n");
        /* Read single character from file */
        ch = fgetc(fPtr);

        /* Print character read code ASCII on console */
        printf ("%d \n", ch);

    } while(ch != EOF); /* Repeat this if last read character is not EOF */


     printf("Closing file ......\n");
    fclose(fPtr);


    return 0;
}

我正在使用包含所有我可以使用的 bin 的 minicom,问题是当我使用 linux 终端和一个简单的 .txt 测试文件时,代码工作得很好。

标签: clinux

解决方案


  1. 正如Zaboj Campula在他的评论中已经说过的那样,EOF 被定义为 -1 的整数。在某些系统上,char 是 0..255 的值,在其他系统上是 -127..128 的值。为避免任何问题,应使用feof()函数(链接)检查流的结尾。由于 char 和 int 的大小不同,这可能是您的问题的根源
  2. 您的代码将打印“文件已成功打开。逐字符读取文件内容。” 对于每个读取的字符。
  3. 只在一个地方保留功能:最后。这使您的代码更具可读性
  4. 当你的部分代码依赖于某些东西时,用错误检查将它括起来。

试试这个代码:

int main() {
    FILE * fPtr;
    char ch;
    int result = 0;

    printf("Opening file ......\n");

    if (!(fPtr = fopen("/flash/etc/output_voice_capture.txt", "r")) {
        printf("Unable to open file.\n");
        printf("Please check whether file exists and you have read privilege.\n");
        result = EXIT_FAILURE;
    } else {
        printf("File opened successfully. Reading file contents character by character.\n");
        while (EOF != (ch = fgetc(fPtr))) {
            printf ("%d \n", ch);
        }

        fclose(fPtr);
    }
    return result;
}

推荐阅读