Reputation: 69
I want to write structures into a Binary file in program A, and then read from it in program B, which prints the structures out. However, I am getting incorrect output.
I've tried fwrite in program A, and fread in program B, then subsequently printed the output using printf, only to get a string of nonsense numbers.
Program 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);
}
Program B (all headers and struct the same, with the following code):
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);
}
I expected the output to be
100
j
50
But the actual output is 172400800
Upvotes: 0
Views: 3847
Reputation: 211740
You're writing trash to your file because you're using the pointer of a pointer, not the pointer.
So you can do a quick fix:
fwrite(one, sizeof(struct record), 1, in);
Or you can rewrite to avoid the allocation, something that's probably a good idea because it's completely unnecessary here:
#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);
}
As an additional note, you really should be steering towards variable names that have intrinsic meaning. one
is not meaningful. r
is an improvement even if somewhat ambiguous, because at least "r" means something in relation to "record".
Upvotes: 3