ekaf
ekaf

Reputation: 153

How fread() and fwrite works in c programming

I am working on a database flat file project using c language. I have created a structure with few members. I am using fwrite() to write them in binary file and fread() to fetch the data. My two major question

1st can we write structure in text file? I have seen no good example. Is it practically wrong to write it in text format? when I write using "w" instead of "wb" I get the text format but with some extra words.

2nd how these fread() & fwrite works(). They operate on a block of data how they get the address of next block. I mean we do have the pointer but file doesnt have any address so how the pointer go to next block?

Upvotes: 1

Views: 911

Answers (1)

Giorgi Moniava
Giorgi Moniava

Reputation: 28654

1st can we write structure in text file ? i have seen no good example .is it practically wrong to write it in text format ?when i write using "w" instead of "wb" i get the text format but with some extra words

Imagine your structure contains some integers inside. Now if you write them using fwrite, these integers will be written in file in binary format. If you try to interpret this as text, this won't work, text editor will try to interpret the binary values as characters - which will most likely not work as you expect.

e.g. if your structure contains integer 3, when written using fwrite, it will be stored as

00000000 0000000 0000000 00000011 (3 in binary)

assuming big endian notation. Now if you will try to read above using a text editor, of course you will not get desired effect.

Not saying anything about the padding bytes which maybe inserted in your structure by compiler.

2nd how these fread() & fwrite works(). They operate on a block of data how they get the address of next block. I mean we do have the pointer but file doesnt have any address so how the pointer go to next block?

This is most likely taken care of using OS.

PS. I suggest you read more about serialization, and try to understand difference between text and binary files.

Upvotes: 1

Related Questions