首页 > 解决方案 > “fread”在读取数字时读取错误值

问题描述

假设我有一个文件:

文件中

3 3

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

#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'};一点,效果很好


任何帮助的尝试表示赞赏

标签: cfilefread

解决方案


fread()用于从文件中读取字节流。3 3如果使用0x33 0x20 0x33ASCII,则使用 3 个字节表示,因此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
}

推荐阅读