Reputation: 723
Below is the structure defined.
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';
I do a fwrite of the following structure in a file. File is opened as below.
fp = fopen("D://tests//t11test.txt","wb");
fwrite(&n, sizeof(B), 1, fp);
The fwrite is successful and I checked the contents of the file corresponding to fp. But when I do a fread on the same file after closing and reopening the file, I am not able to read the contents of the sub-structure m. The fread is
fp = fopen("D://tests//t11test.txt","rb");
fread(&q, sizeof(B), 1,fp);
Where am I going wrong?
Upvotes: 2
Views: 2095
Reputation: 9740
I think you messed up something else, this works:
#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;
}
Output:
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
Upvotes: 1
Reputation: 121961
I can't see what the problem is, but, FWIW, this worked:
#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;
}
Output:
wrote: { { 12, a }, 13, b }
read : { { 12, a }, 13, b }
Upvotes: 1