Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overwrite a file in C?

Tags:

c

file-io

I am trying to overwrite the contents of a FILE in C. Currently I have:

FILE* file  = fopen("filename.txt",  "r+");
fprintf(file, "%d", 1); // regardless of what's in the file, i want to clear it and put 1 in there
...
// legacy code somewhere else in the code base. can't change.
rewind(file);
fprintf(file, "%d", 2);
fflush(file);

However, this will not work properly. The result will be:

1, 21

Each subsequent number will be written to the beginning of the 1. For example:

1, 21, 31, 41, ...

I would like to know if there is a way to always overwrite what's in the file so the following is produced:

1, 2, 3, 4, ...

Any assistance would be appreciated.

Thank you.

EDIT:

I have changed the code to:

FILE* file  = fopen("filename.txt",  "w+");

The problem still persists.

like image 592
czchlong Avatar asked Feb 06 '12 18:02

czchlong


People also ask

How do I overwritten a file?

If you are accustomed to selecting "File -> Save As" when saving documents, you can also overwrite the file with your changes this way. Select "Replace File. This is the same behavior as File Save." The original file will be overwritten.

How do I overwrite data?

You can also overwrite data by replacing old files with new ones. If you are saving a document with the same filename as an already existing document, then the old document will be overwritten by the new one.

Does Fopen overwrite existing file?

fopen() for an existing file in write mode When mode “w” is specified, it creates an empty file for output operations. What if the file already exists? If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file.

Can Fwrite overwrite?

fwrite() does not exactly overwrite by using fseek(). Instead, there are several cases: if the open permissions was 'r' then writing is an error.


1 Answers

You decide that in fopen. Just use "w" or "w+" instead of "r+".

like image 126
Bo Persson Avatar answered Nov 09 '22 23:11

Bo Persson