tags:

views:

137

answers:

2

Let's say I have a text file that is 100 lines long. I want to only change what is in the 50th line.

One way to do it is open the file for input and open a new file for output. Use a for-loop to read in the first half of the file line by line and write to the second file line by line, then write what I want to change, and then write out the second half using a for-loop again. Finally, I rename the new file to overwrite the original file.

Is there another way besides this? A way to modify the contents in the middle of a file without touching the rest of the file and without writing everything out again?

If there is, then what's the code to do it?

+1  A: 

Open the file, use fseek to jump to the place you need and write the data, then close the file.

from http://www.cplusplus.com/reference/clibrary/cstdio/fseek/...

#include <stdio.h>

int main ()
{
  FILE * pFile;
  pFile = fopen ( "example.txt" , "r+" );
  fputs ( "This is an apple." , pFile );
  fseek ( pFile , 9 , SEEK_SET );
  fputs ( " sam" , pFile );
  fclose ( pFile );
  return 0;
}
Fraser Graham
fopen(fname, "w") will erase the existing contents of the file.
Ben Voigt
Oops, that should be "r+" instead of "w"
Fraser Graham
Is there a way to do it without fseek? fseek doesn't work with ofstream. How can it be done with ofstream?
Phenom
+3  A: 

(Copied from my comment on your previous question)

Well, it depends on which I/O library you're using, the C standard library, C++ standard library, or an OS-specific API. But generally there are three steps. When opening the file, specify write access without truncation, e.g. fopen(fname, "r+"). Seek to the desired location with e.g. fseek. Write the new string with e.g. fwrite or fprintf. In some APIs, like Windows OVERLAPPED or linux aio, you can say "write to this location" without a separate seek step.

Ben Voigt