简体   繁体   English

尝试在 C 中使用 fopen 打开文件后程序退出

[英]Program quits after tried to open a file with fopen in C

I'm a newbie programming in C. I'm trying to read the lines of a file.我是 C 编程新手。我正在尝试读取文件的行。 Using the code below, if the file exists, everything is OK.使用下面的代码,如果文件存在,则一切正常。 However, if the file does not exist, the program quits, without any error message.但是,如果该文件不存在,程序将退出,而不会出现任何错误消息。 I expected to get a null in the variable and the program continue running.我希望在变量中得到一个空值并且程序继续运行。

I'm programming in C compiling with gcc in a raspberry with raspbian.我正在用 C 编程,在带有 raspbian 的 raspberry 中使用 gcc 进行编译。

Am I doing somethig wrong?我做错了什么吗?

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);    
}

In case the file is not present, what I want to do is that the program stays running.如果文件不存在,我想要做的是程序保持运行。

You executed fclose(fp);你执行了fclose(fp); regardless of whether fp is NULL .无论fp是否为NULL

Your printf() statement don't have newline, so there are high chance that the string is buffered and not outputted when execution is aborted.您的printf()语句没有换行符,因此很有可能在中止执行时字符串被缓冲而不输出。

You should move fclose(fp);你应该移动fclose(fp); inside the block corresponding to if (fp != NULL) like在对应的块内if (fp != NULL) like

    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); */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM