在尝试用C中的fopen打开文件后,程序退出
我是一个C语言编程新手。我正在尝试读取文件的行。使用下面的代码,如果文件存在,一切正常。但是,如果文件不存在,程序将退出,而不会显示任何错误消息。我希望变量中有一个空值,程序继续运行 我正在用C语言编程,用gcc在raspberry和raspbian中编译 我做错什么了吗在尝试用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;
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