Reputation: 2574
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.
Upvotes: 8
Views: 72212
Reputation: 49
I was going through the same problem. I wanted to overwrite the same file from what I was taking the input. So after trying different methods, I decided to create another pointer that points to the same file. So I have one pointer which reads the input and then I close that using fclose() and I have another pointer for overwriting the same file and again I close that using fclose(). That worked for me.
Upvotes: -1
Reputation: 92211
You decide that in fopen
. Just use "w"
or "w+"
instead of "r+"
.
Upvotes: 20
Reputation: 2314
As far as I can tell, you can't overwrite anything with fprintf. You have to use fwrite, e.g. something like
rewind(file);
char buf[10];
sprintf(buf, "%d", 2);
fwrite(buf, strlen(buf), 1, file);
From your code and question I don't quite follow what it is you actually try to do, but hope this helps (half a year after you asked).
Upvotes: 4