Modify text file
How to just modify 18292.60 to 1111?
#include <stdio.h>#include <stdlib.h>
if ( (fpstream = fopen("sales.txt","a") ) == NULL)
printf("Cannot open sales.txt file.");
The easiest thing to do is to write the whole file out again. I.e.
- Read a piece of data from sales.txt
- Write it out to another file, e.g. temp.txt
- If it needed changing, change it before writing it to the temp file
- Close both files, replace sales.txt with temp.txt
It is possible to modify the file in place without making a copy, by opening it for read and write and then carefully moving the position indicator.
This would be especially painful where the length of the replacement text is not the same as the original, as in your example.
By the way, if you are not restricted to this format for some reason, I suggest that you consider the use of SQLite instead of trying to manage your own flat file database.
To change a field value in a text file you usually read and re-write the whole thing. If you don't want to read the entire file into memory but instead process it a line at a time, you can rename the original file (using a name given by tmpnam), write the lines to a new file with the original name, then remove the original (renamed) file. (The function names in bold are in stdio.h.)
To actually modify the value in place without reading/writing the entire file, you can make it a binary file so that, for instance, the double 1.0 and the double 1.23456789 take up exactly the same amount of space, so you can fseek to the appropriate position and write the new value.