#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/