[b]前言[/b]
最近在工作中遇到一个问题,需要覆盖或者删除指定位置的文件内容,发现网上这方面的资料较少,无奈只能自己解决,下面将自己解决的方法分享给大家,方便大家参考学习,下面话不多说了,来一起看看详细的介绍吧。
[b]一、覆盖指定位置的文件内容[/b]
我们经常使用ofstream或者fstream可写文件,使用ifstream可以写文件,但需要设置文件的打开状态为iOS::out。C++中IO流打开模式使用位掩码来表示。
[b]IO流打开模式有:[/b]
| 成员常量 |
|
| app |
append,追加模式,设置流指针在每一个操作前均指向文件流末尾 |
| ate |
at end,设置流指针在打开时指向文件流末尾 |
| binary |
以二进制模式开打文件流 |
| in |
input,输入模式,允许读取文件流 |
| out |
output,输出模式,允许写入文件流 |
| trunc |
truncate,截断模式,打开文件流时清空所有内容 |
些常数在ios_base类定义为public成员。因此,可以直接以类名字加作用域运算符访问(如[code]ios_base::out[/code]),或使用ios_base的任何继承类或实例化的对象,例如[code]ios::out[/code]或[code]cout.out [/code]。
ofstream在打开文件时默认清空文件所有内容。如果使用[code]ios::app[/code]来打开文件,虽然不会清空文件内容,但是每次写操作都追加到文件末尾。
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;
}
上面的操作虽然使用了文件指针偏移操作[code]fout.seekp(-5,ios::end);[/code] ,但是每次写入还是追加到文件末尾,解决办法使用文件打开模式[code]ios::in[/code],这样可以保证文件内容不会被清空,且文件指针偏移操作有效。
fout.open("hello.txt",fstream::binary | fstream::out | fstream::in);
//或
fstream fout("hello.txt",fstream::binary | fstream::out | fstream::in);
[b]二、删除指定位置的文件内容[/b]
很遗憾,C++的文件流并没有提供这样的功能,我们只能先读取保留的内容,再以截断模式写回原文件[3]。
[b]总结[/b]
好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对编程素材网的支持。
[b]参考文献[/b]
[1][url=https://stackoverflow.com/questions/7300306/c-overwriting-data-in-a-file-at-a-particular-position]C++ overwriting data in a file at a particular position[/url]
[2][url=http://www.cplusplus.com/reference/ios/ios_base/openmode/]std::ios_base::openmode[/url]
[3][url=https://stackoverflow.com/questions/13112026/overwriting-some-text-in-a-file-using-fstream-and-delete-the-rest-of-the-file]overwriting some text in a file using fstream and delete the rest of the file[/url]