C Programming - Structures, Unions, Enums - Discussion

Discussion Forum : Structures, Unions, Enums - Yes / No Questions (Q.No. 1)
If the following structure is written to a file using fwrite(), can fread() read it back successfully?
struct emp
    char *n;
    int age;
struct emp e={"IndiaBIX", 15};
FILE *fp;
fwrite(&e, sizeof(e), 1, fp);
Answer: Option
Since the structure contain a char pointer while writing the structure to the disk using fwrite() only the value stored in pointer n will get written. so fread() fails to read.
7 comments Page 1 of 1.

SHI said:   6 years ago
I agree @Tonyg. Option B is correct.

Zdd said:   6 years ago
I agree with @Tonyg.

In another program, we cannot use fread() to read it back.

So, Option B is correct.

Selluboy said:   7 years ago
Yes. As Roman said, Option A is correct. We can read the contents of structure that is written through one file using another program file.

TonyG said:   8 years ago
Option B is correct.

What Roman points out above is correct, but the question is ambiguous.

The question is referring to a separate program reading it back.

When a separate program is reading it back with an freed and will only receive the value of the pointer. N will not point to anything useful.

Roman said:   10 years ago
Option A is right. The structure contain pointer. Not value, but pointer itself will be written/read. Verified with gcc.

fp = fopen("my.bin", "w");
fwrite(&ew, sizeof(ew), 1, fp);
printf(" ew %s, %d\n", ew.n, ew.age);
fp = fopen("my.bin", "r");
fread(&ew, sizeof(ew), 1, fp);
printf(" ew %s, %d\n", ew.n, ew.age);


ew IndiaBIX, 15
ew IndiaBIX, 15

Swathireddy said:   1 decade ago
Explain about where we use fwrite(), fread().

Ann said:   1 decade ago
Please explain the concept.

Post your comments here:

Your comments will be displayed after verification.