Namratha
Namratha

Reputation: 16780

rewind(file pointer) and then fwrite. Won't fwrite overwrite the file contents? C

I came acroos this somewhere.

A file is being written and then rewind(fileptr) is done and then what should be written to the beginning of the file is written. But writing at the beginning, won't it overwrite the contents of the file? Please advise.

Upvotes: 0

Views: 2660

Answers (1)

DigitalRoss
DigitalRoss

Reputation: 146053

Technically, yes

Yes, the file will be overwritten, but only for the length of the write. If the file is longer, in most cases (ordinary files on mainstream systems) the remaining bytes will be unchanged.

However, you may actually be wondering if the file will be truncated at that point: usually (same cases) no. Technically, truncation is implementation-defined for text files, and no for binary files.

I would be surprised if a modern system even had a text-vs-binary distinction, certainly Unix, Linux, and BSD systems don't, and I suspect that the implementation-defined weasel-words were put in for some now-decommissioned fossil. If so, then in all important cases the remaining bytes will be unchanged and the file will not be truncated.

Now, the file API is used for many things that don't implement the complete list of file abstractions: think UDP sockets, terminals, tape drives, random controllers for non-storage hardware, etc. It would be unwise, to say the least, to even use a buffered I/O package to write such channels, but perhaps they are the reason for the gap in the specification.

Upvotes: 4

Related Questions