Search code examples
cfopen

Modifying content of a text file in C


I understand that in C, if I have an existing text file "test.txt", calling fopen("test.txt","w") will overwrite the existing content of "test.txt".

I am trying to find an efficient way about my problem: Suppose that I have 10 rows in test.txt with each row containing a number. test.txt can refer to the values of the inputs to a PDE solver that I have. I want to do a sensitivity analysis on the last 3 parameters, i.e. keeping the first 7 numbers in test.txt fixed, I want to try different values for the last 3 rows. Hence, I will be writing to test.txt in a for loop but I only intend to change the values of the last 3 rows at every iteration. The append of fopen does not work for me. Is there a more efficient way to go about this than storing the first seven values in an array and having to rewrite these values in the for loop through fopen?

Suggestions appreciated.


Solution

  • Hence, I will be writing to test.txt in a for loop but I only intend to change the values of the last 3 rows at every iteration. The append of fopen does not work for me. Is there a more efficient way to go about this than storing the first seven values in an array and having to rewrite these values in the for loop through fopen?

    It seems like you're going to need to read in and store the first seven values anyway. You can, indeed, avoid rewriting them, however. First, open the file in read / write mode without truncation:

    FILE *input = fopen("test.txt", "r+");
    

    Read / write mode differs from append mode ("a" or "a+") in that in the former case, the file is initially positioned at the beginning and writes always go to the current file position, whereas in the latter case, the file is initially positioned at the end, and writes always go to the end.

    Having opened the file in an appropriate mode, read it line by line, e.g. with fgets(). After the seventh line, use ftell() to record the current file position for later reference. To overwrite the last lines, use fseek() to return to the recorded position, and just write the new values. This may leave junk at the end of the file, after the last line; if that will be a problem then you can overwrite the tail (e.g. with space characters). POSIX also has ftruncate() which you could use to clip any tail, but that's not part of standard C.