c - 尝试在 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);
}
如果文件不存在,我想做的是程序保持运行。
解决方案
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); */
推荐阅读
- linux - sed 不能正确地从 UTF 范围中删除字符
- c++ - 为什么要更改这两个代码的输出中的“&”字符?
- c++ - C++ 在最后一个循环中排除部分循环运算符
- ruby-on-rails - 了解 rails 与 Puma 和 Capybara 的冲突。如何在 Gemfile 中正确安装 puma?
- sql - 在 TYPO3 viewHelper 中获取数据库记录
- java - 使用谷歌云端点时,有没有办法限制对端点的访问和可见性?
- java - 在我的 IntelliJ 项目中使用 Maven 资源时遇到问题
- regex - reg-expression : 与 \t \n \r 的单词边界
- python - 如何在不显示 dtype 的情况下从对象打印 Python?
- python - 将表单数据写入 SQLLite 数据库