这个错误描述在 fread() 中意味着什么
what this error description means in fread()
我正在 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"是我系统中的一个文件。
我所知道的是它在 fread() 上失败,因为 "Read_error" 弹出。但是这个 "Success" 是什么意思?如果失败了,为什么会给出 "Success" 字样?
关于如何使用 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
文件可能是空的,那么它将 return 0
!
如果您读取的计数不足(即项目少于您的预期),则 fread()
遇到错误或在读取足够的字节之前已到达文件末尾。
在您的情况下,您读取了 0 个项目而不是 1 个项目,因此在读取整个项目之前出现错误或遇到文件结尾。使用 feof() 或 ferror() 来确定您是否有文件结尾或错误。即,如果 ferror()
returns 非零,则出现错误并且 errno
有意义。
我正在 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"是我系统中的一个文件。 我所知道的是它在 fread() 上失败,因为 "Read_error" 弹出。但是这个 "Success" 是什么意思?如果失败了,为什么会给出 "Success" 字样?
关于如何使用 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
文件可能是空的,那么它将 return 0
!
如果您读取的计数不足(即项目少于您的预期),则 fread()
遇到错误或在读取足够的字节之前已到达文件末尾。
在您的情况下,您读取了 0 个项目而不是 1 个项目,因此在读取整个项目之前出现错误或遇到文件结尾。使用 feof() 或 ferror() 来确定您是否有文件结尾或错误。即,如果 ferror()
returns 非零,则出现错误并且 errno
有意义。