Writing to specific position in a file

2019-08-14 17:26发布

I have

fstream output;
output.open(fname, ios::out | ios::trunc); //file
for (int i=0; i<flength; i++)
    output.put('1');

I want to overwrite different length of data to different locations in the file. Data is characters.

Lets say there is 111111111111111111111111111111111, I want to write

11   111111333111!!!!!!1    11441111

标签: c++ file
5条回答
男人必须洒脱
2楼-- · 2019-08-14 18:10

Check out ostream::seekp, here. Position the file-pointer to the desired location before writing.

查看更多
forever°为你锁心
3楼-- · 2019-08-14 18:13

You can use seekp to set the position of the put pointer and write at the specific position in the file, e.g.

 output.seekp(10);
 output.put('!');
查看更多
小情绪 Triste *
4楼-- · 2019-08-14 18:17

Use seekp() to set the writing position in the file stream.

查看更多
该账号已被封号
5楼-- · 2019-08-14 18:19

You can't "insert" things in the middle of the file - the only inplace operations you can do is writing the exact same amount of bytes that you are trying to overwrite, i.e. writing without changing the length of the file. If you need to write a string of different length (as in your example) you have to rewrite the whole file from the point where you ended your write operation (store original in a buffer and rewrite).

查看更多
地球回转人心会变
6楼-- · 2019-08-14 18:21

The Best way is to rewrite the whole file into another file after making required changes.

std::ifstream fin("yourfile.txt");
remove("yourfile.txt");

Copy the stream before removing your file. This can help you preserve the name of the file.

查看更多
登录 后发表回答