我正在尝试编写一个使用fstream读取文件的程序 然后,重写一些文本并删除文件的其余部分 这是我正在尝试的代码
#include<iostream>
#include<fstream>
using namespace std;
int main(int argc, char **argv){
fstream *binf;
fstream someFile("t.txt", ios::binary|ios::out|ios::in);
int i;
for(i=0;i<3;i++){
char c;
someFile.seekg(i);
someFile.get(c);
cout<<"c:"<<c<<endl;
}
someFile.seekp(i++);
someFile.put("Y");
someFile.seekp(i++);
someFile.put("Y");
//Delete the rest of the file
return 0;
}
请注意以下用于打开文件的标志
ios::in Open for input operations.
ios::out Open for output operations.
ios::binary Open in binary mode.
ios::ate Set the initial position at the end of the file. If this flag is not set to any value, the initial position is the beginning of the file.
ios::app All output operations are performed at the end of the file, appending the content to the current content of the file. This flag can only be used in streams open for output-only operations.
ios::trunc If the file opened for output operations already existed before, its previous content is deleted and replaced by the new one.
我尝试了很多这些的组合,但是没有它们可以帮助我做我想做的事 我想读文件,直到找到文字。如果我找到了我想要的文本,我会过度编写并删除文件的其余部分。因此,应该将文件重新调整为较小的文件。
答案 0 :(得分:2)
单流对象无法做到这一点。
可能的解决方案:
关闭文件并调用truncate函数:
#include <unistd.h>
int ftruncate(int fildes, off_t length);
int truncate(const char *path, off_t length);
MS Windows截断版本为_chsize
- 请参阅http://msdn.microsoft.com/en-us//library/dk925tyb.aspx
int _chsize(
int fd,
long size
);
或者打开你的文件只读,读取/替换一些stringstream,然后把这一切都放到你的文件这次打开覆盖:
fstream someFile("t.txt", ios::binary|ios::in);
stringstream ss;
// copy (with replacing) whatever needed from someFile to ss
someFile.close();
someFile.open("t.txt", ios::binary|ios::out|ios::trunc);
someFile << ss.rdbuf();
someFile.close();