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

Writing a struct into a file but reading it incorrectly

#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 读取,但是您可以在可打开读写的文件中读取,甚至可以 replace 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);

}