开发者

Is modifying a file without writing a new file possible in c++? [duplicate]

开发者 https://www.devze.com 2022-12-24 03:55 出处:网络
This question already has answers here: 开发者_运维问答 How to overwrite only part of a file in c++
This question already has answers here: 开发者_运维问答 How to overwrite only part of a file in c++ (3 answers) Closed 7 years ago.

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?


(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.


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消