我正在 Ubuntu 上学习 fopen(),这是我的代码。请问具体失败原因是什么?
a.c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
int main() {
char reg_filename[] = "/home/chuck/Documents/enable";
FILE* f;
char val[2];
f = fopen(reg_filename, "r");
if (f == NULL) {
perror(reg_filename);
printf("error\n");
return 1;
}
setvbuf(f, (char *)NULL, _IONBF, 0);
if (fread(&val, sizeof(val), 1, f) == 0) {
perror(reg_filename);
printf("Read_error\n");
return 1;
}
return 0;
}
构建并运行它...
chuck@ubuntu:~/Documents$ gcc a.c
chuck@ubuntu:~/Documents$ ./a.out
/home/chuck/Documents/enable: Success
Read_error
在代码中,“enable”是我系统中的一个文件。 我所知道的是,由于“Read_error”弹出,它在 fread() 上失败。但这个“成功”意味着什么呢?如果失败了,为什么会显示“成功”字样?
关于如何使用 fread(),我是全新的...这个 fread() 将从 f(文件路径)读取 val[] 长度的大小并读取到 val[],对吧?
它与 val[] 大小有关吗?在这种情况下,我只是将其设置为 2,那么 sizeof(val) 应该为 3?那么 fread 如何将 f (/home/chuck/Documents/enable) 读入其中呢?
最佳答案
阅读 fread
的手册页
size_t fread(void *ptr, size_t size, size_t nmembFILE *" stream );
它明确指出,
The function fread() reads nmemb items of data, each size bytes long, from the stream pointed to by stream, storing them at the location given by ptr.
重要的是,您可能想要更改
fread(&val, sizeof(val), 1, f)
到
fread(val, sizeof(val), 1, f)
因此,如果您的 enable
文件可能为空,它将返回 0
!
关于c - 这个错误描述在 fread() 中意味着什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49918451/