我想在程序 A 中将结构写入二进制文件,然后在程序 B 中从中读取,打印出结构。但是,我得到的输出不正确。
我在程序A中试过fwrite,在程序B中试过fread,然后用printf打印输出,结果得到一串无意义的数字。
程序A:
#include <stdio.h>
#include <stdlib.h>
struct record
{
int index;
char name [100];
int age;
};
int main ()
{
struct record *one=malloc(sizeof(struct record));
FILE *in=fopen("records.bin", "ab+")l
fgets(one->name, 100, stdin);
one->index=100;
one->age=50;
fwrite(&one, sizeof(struct record), 1, in);
fclose(in);
}
程序B(所有头文件和结构相同,代码如下):
int main ()
{
FILE *in=fopen("records.bin", "rb+");
struct record array;
fread (&array, sizeof(struct record), 1, in);
printf ("%d\n", array.index);
printf ("%s\n", array.name);
printf ("%d\n", array.age);
fclose(in);
}
我期望输出是
100
j
50
但实际输出是172400800
最佳答案
您正在向文件中写入垃圾,因为您使用的是指针的指针,而不是指针。
所以你可以快速修复:
fwrite(one, sizeof(struct record), 1, in);
或者您可以重写以避免分配,这可能是个好主意,因为在这里完全没有必要:
#include <stdio.h>
#include <stdlib.h>
struct record
{
int index;
char name [100];
int age;
};
int main ()
{
struct record one;
FILE *in = fopen("records.bin", "ab+");
fgets(one.name, 100, stdin);
one.index=100;
one.age=50;
fwrite(&one, sizeof(struct record), 1, in);
fclose(in);
}
作为附加说明,您确实应该转向具有内在含义的变量名称。 one
没有意义。 r
是一种改进,即使有点模棱两可,因为至少“r”意味着与“记录”相关的东西。
关于c - 在C中读取和写入结构到二进制文件,然后打印结构元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56173740/