Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在尝试用C中的fopen打开文件后,程序退出_C_File_Exception - Fatal编程技术网

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

在尝试用C中的fopen打开文件后,程序退出,c,file,exception,C,File,Exception,我是一个C语言编程新手。我正在尝试读取文件的行。使用下面的代码,如果文件存在,一切正常。但是,如果文件不存在,程序将退出,而不会显示任何错误消息。我希望变量中有一个空值,程序继续运行 我正在用C语言编程,用gcc在raspberry和raspbian中编译 我做错什么了吗 void readValues(void) { FILE * fp; char * line = NULL; size_t len = 0; ssize_t read; int i=0;

我是一个C语言编程新手。我正在尝试读取文件的行。使用下面的代码,如果文件存在,一切正常。但是,如果文件不存在,程序将退出,而不会显示任何错误消息。我希望变量中有一个空值,程序继续运行

我正在用C语言编程,用gcc在raspberry和raspbian中编译

我做错什么了吗

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);    
}
如果文件不存在,我想做的是程序保持运行。

您执行的
fclose(fp)无论
fp
是否为
NULL

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

你应该移动
fclose(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); */

注意:您不需要
if(line)
,因为
free()
被定义为在传递
NULL
时不执行任何操作。我根据您的示例更改了代码,现在它可以工作了。谢谢:D