下面是定义的结构。
typedef struct{
int a;
char b;
}X;
typedef struct{
X m;
int c;
char d;
}B;
B n,q;
n.m.a = 12;
n.m.b = 'a';
n.c = 13;
n.d = 'b';
我在文件中写入以下结构。文件打开如下。
fp = fopen("D://tests//t11test.txt","wb");
fwrite(&n, sizeof(B), 1, fp);
fwrite成功,查看了fp对应的文件内容。 但是,当我在关闭并重新打开文件后对同一文件执行 fread 时,我无法读取子结构 m 的内容。最可怕的是
fp = fopen("D://tests//t11test.txt","rb");
fread(&q, sizeof(B), 1,fp);
我哪里出错了?
最佳答案
我看不出问题是什么,但是,FWIW,这有效:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
typedef struct{ int a; char b; }X;
typedef struct{ X m; int c; char d; }B;
void print_B(B* a_b)
{
printf("{ { %d, %c }, %d, %c }",
a_b->m.a,
a_b->m.b,
a_b->c,
a_b->d);
}
int main()
{
/* Write structure. */
{
FILE* fp;
B n;
n.m.a = 12;
n.m.b = 'a';
n.c = 13;
n.d = 'b';
fp = fopen("x.dat", "wb");
assert(0 != fp);
if (1 != fwrite(&n, sizeof(B), 1, fp))
{
fprintf(stderr, "Failed to fwrite(): %s\n", strerror(errno));
return 1;
}
fclose(fp);
printf("wrote: ");
print_B(&n);
printf("\n");
}
/* Read structure. */
{
FILE* fp;
B q;
fp = fopen("x.dat", "rb");
assert(0 != fp);
if (1 != fread(&q, sizeof(B), 1, fp))
{
fprintf(stderr, "Failed to fread(): %s\n", strerror(errno));
return 1;
}
fclose(fp);
printf("read : ");
print_B(&q);
printf("\n");
}
return 0;
}
输出:
wrote: { { 12, a }, 13, b }
read : { { 12, a }, 13, b }
关于c - 从文件中读取结构内的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9699406/