从文件读取结构内的结构
问题描述:
下面是定义的结构。从文件读取结构内的结构
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';
我在文件中做了以下结构的fwrite。文件打开如下。
fp = fopen("D://tests//t11test.txt","wb");
fwrite(&n, sizeof(B), 1, fp);
fwrite成功,我检查了与fp对应的文件内容。 但是,当我关闭并重新打开文件后在同一文件上执行fread时,我无法读取子结构m的内容。该fread是
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 }
+0
感谢您的回答。它的工作..我会让你知道我的问题。 – 2012-03-14 10:25:41
+0
没问题,有兴趣找出问题所在。 – hmjd 2012-03-14 10:26:40
答
我想你搞砸了别的东西,这个工程:
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
typedef struct{
int a;
char b;
} X;
typedef struct{
X m;
int c;
char d;
} B;
int main() {
FILE *fd;
B n, q;
n.m.a = 12;
n.m.b = 'a';
n.c = 13;
n.d = 'b';
if((fd = fopen("test.dat", "wb")) == NULL) {
fprintf(stderr, "Error opening file: %s\n", strerror(errno));
exit(-1);
}
fwrite(&n, sizeof(n), 1, fd);
fclose(fd);
if((fd = fopen("test.dat", "rb")) == NULL) {
fprintf(stderr, "Error opening file: %s\n", strerror(errno));
exit(-1);
}
fread(&q, sizeof(q), 1, fd);
fclose(fd);
printf(
"n.m.a: %d, q.m.a: %d; n.m.b: %c, q.m.b: %c; n.c: %d, q.c: %d; n.d: %c, q.d: %c\n",
n.m.a, q.m.a, n.m.b, q.m.b, n.c, q.c, n.d, q.d
);
return 0;
}
输出:
n.m.a: 12, q.m.a: 12; n.m.b: a, q.m.b: a; n.c: 13, q.c: 13; n.d: b, q.d: b
你是什么意思“不能读”? – 2012-03-14 09:49:00
我猜你已经用一种破坏原始文件内容的模式重新打开文件。你可以发布一个复制程序吗? – sarnold 2012-03-14 09:49:55
@ Karoly值** int c **和** char d **正确读取。子结构X **的**成员没有正确阅读。 @sarnold我以“wb”模式写入文件,并在“rb”中重新打开以读取结构。其实我有两个程序。一个将结构写入文件,另一个读取结果。 – 2012-03-14 09:52:36