How do I override or delete the contents of a file in a specified location with C++

  • 2020-05-27 06:33:37
  • OfStack

preface

Recently, I encountered a problem in my work. I need to cover or delete the file content of the designated location. I found that there are few materials in this field on the Internet, so I have to solve it by myself.

1. Overrides the file contents of the specified location

We often use ofstream or fstream to write files, ifstream to write files, but you need to set the open state of the file to iOS::out. The IO flow open mode in C++ is represented by a bitmask.

IO flow open mode:

成员常量
app append,追加模式,设置流指针在每1个操作前均指向文件流末尾
ate at end,设置流指针在打开时指向文件流末尾
binary 以2进制模式开打文件流
in input,输入模式,允许读取文件流
out output,输出模式,允许写入文件流
trunc truncate,截断模式,打开文件流时清空所有内容

Some constants in the ios_base class are defined as public members. Therefore, you can access it directly with the class name plus a scoping operator (e.g ios_base::out ), or any inherited class or instantiated object that USES ios_base, for example ios::out or cout.out .

ofstream clears all file contents by default when opening a file. If you are using ios::app To open the file. It does not empty the file, but each write is appended to the end of the file.


int main(){
 fstream fout;
 fout.open("hello.txt",fstream::binary | fstream::out | fstream::app);
 pos=fout.tellp();
 fout.seekp(-5,ios::end);
 fout.write("####",4);
 fout.close();
 return 0;
}

The above operation USES the file pointer offset operation fout.seekp(-5,ios::end); , but each write is still appended to the end of the file, and the solution USES file open mode ios::in , which ensures that the contents of the file are not emptied and that the file pointer offset operation is valid.


fout.open("hello.txt",fstream::binary | fstream::out | fstream::in);

// or 
fstream fout("hello.txt",fstream::binary | fstream::out | fstream::in);

2. Delete the file contents in the specified location

Unfortunately, the C++ file stream does not provide such functionality, so we can only read the reserved content first and then write back to the original file in truncated mode [3].

conclusion

reference

[1]C++ overwriting data in a file at a particular position

[2]std::ios_base::openmode

[3]overwriting some text in a file using fstream and delete the rest of the file


Related articles: