首页 > 解决方案 > 尝试在 C 中使用 fopen 打开文件后程序退出

问题描述

我是 C 中的新手编程。我正在尝试读取文件的行。使用下面的代码,如果文件存在,则一切正常。但是,如果该文件不存在,程序将退出,而不会出现任何错误消息。我希望在变量中得到一个 null 并且程序继续运行。

我正在用 raspbian 在树莓中用 gcc 编译 C 语言。

我做错了什么吗?

void readValues(void)
{
    FILE * fp;
    char * line = NULL;
    size_t len = 0;
    ssize_t read;
    int i=0;
    
    fp = fopen("/tmp/valores.txt", "r");
    // If the file valores does not exist, the execution quits here

    if (fp != NULL)
    {
       while ((read = getline(&line, &len, fp)) != -1)
       {
           printf("%s", line);
           values[i] = atoi(line);
        
           i++;
        }
    }
    else
    {
        printf("Could not open file");
    }

    fclose(fp);
    if (line)
        free(line);    
}

如果文件不存在,我想做的是程序保持运行。

标签: cfileexception

解决方案


fclose(fp);无论是否fp为,您都执行了NULL

您的printf()语句没有换行符,因此在执行中止时字符串很有可能被缓冲并且不输出。

您应该在与likefclose(fp);对应的块内移动if (fp != NULL)

    if (fp != NULL)
    {
       while ((read = getline(&line, &len, fp)) != -1)
       {
           printf("%s", line);
           values[i] = atoi(line);
        
           i++;
        }
        fclose(fp); /* add this */
    }
    else
    {
        printf("Could not open file");
    }

    /* remove this */
    /* fclose(fp); */

推荐阅读