c - 将结构写入文件但读取不正确

标签 c struct io fwrite fread

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Student
{
    int id;
    int grade;
};

struct Student john;

int main()
{

    john.id = 100;
    john.grade = 80;

    struct Student steve;

    fwrite(&john, sizeof(struct Student), 1, stdout);
    fread(&steve, sizeof(struct Student), 1, stdout);

    printf("\n%d %d \n", steve.id, steve.grade);

    return 0;
}

我正在尝试将 struct 写入文件(在本例中为标准输出),然后我尝试读取它。

它打印的值是随机的,这可能是什么原因?

最佳答案

正如评论中已经指出的,您无法从 stdout 读取,但是您可以在可打开读写的文件中执行此操作,您甚至可以替换 stdout 带有此类文件,例如在 UNIX 中使用未命名管道,chek C language. Read from stdout .

但是,您仍然需要在写入后重新定位文件偏移量,以便可以从文件的开头读取,例如:

int main()
{

    john.id = 100;
    john.grade = 80;

    FILE* f = fopen("test", "w+"); // check return value..

    struct Student steve;

    fwrite(&john, sizeof(struct Student), 1, f); // same here...

    fseek(f, 0, SEEK_SET); // <-- reset offset, (or lseek if you're using a file descritor)

    fread(&steve, sizeof(struct Student), 1, f); // and here

    printf("\n%d %d \n", steve.id, steve.grade);

    fclose(f);

}

关于c - 将结构写入文件但读取不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66941482/

相关文章:

c - MAC OS X : zsh: no such file or directory once running a program from Codeblocks

struct - 有没有办法在 Rust 中获取 `struct` 的地址?

struct - golang 对导入库的未定义函数调用

java - FileOutStream.write(byte[]) 总是阻塞吗?

java - 如何使用 Blobstore 输入流读取连续的换行分隔文本行?

C - 打印素数列表(递归)

c - sscanf - 不同数量的格式参数?

clock() 在 C 中返回一个负值

c - 使用内存分配构造指针

java - 读取xml文件后防止文件 channel 关闭