【问题标题】:"fread" reads wrong values when it's reading numbers“fread”在读取数字时读取错误值
【发布时间】:2021-05-27 20:14:46
【问题描述】:

假设我有一个文件:

file.in

3 3

我想读取其中写有fread的2个数字,所以我写了这个:

#include <stdio.h>

int main() {
    int buffer[3] = {0}; // 3 items bcs it also reads the space between the "3"s
    FILE* f = fopen("file.in", "r");

    fread(buffer, 3, 4, f);

    printf("%d %d", buffer[0], buffer[2]);
}

我认为输出应该是3 3,但我的想法类似于17?????? 17??????。但是,如果我将int buffer[3] = {0}; 设置为char buffer[3] = {'\0'}; 它工作正常


任何帮助的尝试表示赞赏

【问题讨论】:

  • 等等,你的文件有代表十进制数字的 ascii 字符?或者它有原始的二进制有符号 32 位值?
  • 您正在读取二进制文件,但以 ascii 格式打开文件。你的数据是二进制还是 ascii?
  • @Devolus 如何检查它是用二进制还是 ascii 编写的?
  • 在您的fopen 电话中,您当前使用"r"。对于二进制文件,它应该是"rb"。编写文件时也是如此。

标签: c file fread


【解决方案1】:

fread() 用于从文件中读取字节流。如果使用 ASCII,3 3 使用 3 字节 0x33 0x20 0x33 表示,因此 fread(buffer, 3, 4, f);(读取 12 字节)不适用于读取此内容。

如果你想将字节存储在int,你应该使用fgetc()

#include <stdio.h>

int main() {
    int buffer[3] = {0}; // 3 items bcs it also reads the space between the "3"s
    FILE* f = fopen("file.in", "r");

    for (int i = 0; i < 3; i++) {
        buffer[i] = fgetc(f);
    }

    printf("%c %c", buffer[0], buffer[2]); // use %c instead of %d to print the characters corresponding to the character codes
}

【讨论】:

  • 我认为fgetc返回char,例如在这种情况下它会返回'3'' ''3'
  • @platinoob_返回的东西是正确的,但是fgetc()返回int
  • 我试过了,它给了我chars,我需要这些数字在以后的实际程序中做某些事情,比如制作一个矩阵(char* matrix = (char*)calloc(buffer[0], 1); for (int i = 0; i &lt; buffer[0]; i++) {matrix[i] = (char*)calloc(buffer[2], 1);}),如果不是@ 987654340@, file.in123 132?
  • @platinoob_你应该使用fscanf()或者自己解析文件。
  • 其实我已经完成了程序,这就是我最后所做的,只是我在某处看到fread更快的bcs我只是在研究使用fread的情况
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-11
  • 1970-01-01
  • 2019-03-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多