根据手册页fclose(3):
返回值
成功完成后返回0.否则,
EOF返回并设置全局变量errno以指示错误.在任何一种情况下fclose(),对流的任何进一步访问(包括另一次调用)都会导致未定义的行为.错误
EBADF底层文件描述符fp无效.该
fclose()函数也可能失败并设置errno为例程指定的任何错误close(2),write(2)或fflush(3).
当然fclose(NULL)应该失败,但我希望它能够errno正常返回,而不是直接通过分段故障死亡.这种行为有什么原因吗?
提前致谢.
更新:我将把我的代码放在这里(strerror()特别是我正在努力).
FILE *not_exist = NULL;
not_exist = fopen("nonexist", "r");
if(not_exist == NULL){
printError(errno);
}
if(fclose(not_exist) == EOF){
printError(errno);
}
Run Code Online (Sandbox Code Playgroud) 我有这个功能:
void aggiornadatabase(void) {
FILE* fp;
int c=0;
char str[30];
int m;
sprintf(str, "%s.csv", utenti[posizioneuser].id);
printf("%s\n", str);
fp = fopen(str, "w");
if (fp == NULL)
printf("Database error\n");
else
m = remove(str);
if (m == 0)
printf("Success\n");
else
printf("Unable to delete the File\n");
fclose(fp);
}
Run Code Online (Sandbox Code Playgroud)
执行此函数时,它会删除所选.csv文件中的所有内容,但它不会删除文件本身(实际上它会打印"无法删除文件").
为什么会这样?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char line[80];
FILE *in = fopen("spooky.csv", "r");
FILE *file1 = fopen("ufos.csv", "w");
FILE *file2 = fopen("disappearances.csv", "w");
FILE *file3 = fopen("others.csv", "w");
while (fscanf(in, "%79[^\n]\n", line) == 1) {
if (strstr(line, "UFO"))
fprintf(file1, "%s\n", line);
else if (strstr(line, "Disappearance"))
fprintf(file2, "%s\n", line);
else
fprintf(file3, "%s\n", line);
}
fclose(file1);
fclose(file2);
fclose(file3);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
此代码返回分段错误的运行时错误。
我在什么硬件上编译这个程序有关系吗?我使用的是带有 Intel Core i7(第七代)的 Fedora 38(工作站)。