c - 这个错误描述在 fread() 中意味着什么

标签 c ubuntu 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”是我系统中的一个文件。 我所知道的是,由于“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/

相关文章:

c - 我应该明确定义我的枚举常量的值吗

c++ - C/C++ malloc 一 block 内存,然后将不同的部分用于不同的任意类型

C: Xcode 和 VS2015 中的复数

git提示在Android Studio终端中不起作用

c++ - scanf/sscanf 可以处理转义字符吗?

java - 复制到全局剪贴板不适用于 Ubuntu 中的 Java

linux - 无法在终端代码中为带连字符 (-) 的用户名添加密码

c - 在 C 中用 fread 和 fwrite 提问

逐字节比较两个文件

php - 如何使用 php 将 jpg 图像转换为正确的 blob 数据类型