Rahul
Rahul

Reputation: 995

how fwrite() works in c files?

fwrite() is used to write structure to the file in c, suppose we have following structure:

struct student{
int rollno;
char name[20],grade;
float total;
};

Upvotes: 0

Views: 1491

Answers (2)

Déjà vu
Déjà vu

Reputation: 28850

fwrite is a C function and deals with structures the way other functions do, without doing any special treatment (unless requested). It takes that struct as a binary object, and writes as many bytes as you want of it.

does it write full sizeof(struct tudent)bytes to the file every time we write it with fwrite()?

It writes the size you ask fwrite to write, so if it's sizeof(structX) it writes that size. If you do the same fwrite twice, it will be written twice.

if so then does it write name with 20 bytes of storage on the file even if you have only stored few characters in the name?

name is declared as char[20] which takes 20 bytes. So yes that part takes 20 bytes on disk (even if the "string" contains "only" 3 characters (i.e. a '\0' is at the 4th position), all 20 bytes are written).

if that is the case then can we modify the the written record using fread() with other functions such as fputs() fputc() putw(), but these function doesnt seem to modify the record correctly?

putw writes a word to the stream, meaning an int as it is (a binary word, not its string representation), but better use fwrite as recommended in the man page. fputc writes a unique character. fputs writes a null-terminated string, unlike fwrite which writes the number of characters you require regardless if a zero-byte is hidden somewhere in it.

Upvotes: 3

Sam Pagenkopf
Sam Pagenkopf

Reputation: 258

All that fwrite is able to see is the struct in memory. It does not know the name of the fields, their offsets, or any related info. All it can do is essentially write your memory directly into a file. So, it will write all 20 bytes of your string, along with the rest of your struct.

If you want it to write things in a human-readable form, you must write a function that knows about each field and formats them.

This is because C does not possess something called "reflection", which allows the program to store and utilize information such as the name or type of a variable or field, and use that information at runtime. There are other languages, like golang, that are able to do such things.

Upvotes: 2

Related Questions