C Programming - Structures, Unions, Enums - Discussion

Discussion Forum : Structures, Unions, Enums - Yes / No Questions (Q.No. 1)
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);
Yes
No
Answer: Option
Explanation:
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.
Discussion:
8 comments Page 1 of 1.

Anil kumar arikicherla said:   9 months ago
I think here is a syntax error;

fwrite(&e, sizeof(e), 1, fp);
insted; fwrite(&e, sizeof(e), fp); =>this would be the correct one.

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

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

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

So, Option B is correct.

Selluboy said:   8 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:   9 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:   1 decade 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);
fclose(fp);
fp = fopen("my.bin", "r");
fread(&ew, sizeof(ew), 1, fp);
fclose(fp);
printf(" ew %s, %d\n", ew.n, ew.age);

Output:

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.