【发布时间】:2012-04-20 09:35:10
【问题描述】:
我有一些内部文件,只能附加到每个附加 \n 字符后添加到文件中。但从理论上讲,附加到文件可能会失败并损坏。这就是为什么每次打开文件时我都想在最后一个 EOL 之后寻找它的最后一个有效位置。此代码将执行此操作:
// Not using ios::app instead of ios::ate | ios::out because it will
// put print pointer to the EOF every time before writing.
fstream file(name.c_str(), ios::binary | ios::ate | ios::out | ios::in);
if(!file.is_open()) {
cerr << "Error in oppening file " << name << endl;
exit(EXIT_FAILURE);
} else {
while(0 != file.tellp()) //if file is not empty
{
file.seekg(-1, ios_base::cur);
if(0 == file.tellg() || file.get() == '\n') {
break;
}
file.seekg(-1, ios_base::cur);
}
file.seekp(of.tellg());
}
//{1}
//Use file for appending to...
但是如果应该附加到文件的部分的长度小于从文件中最后一个 EOL 字符开始的部分的长度,它将无法正常工作。这就是为什么在{1} 位置我想删除从file.tellp() 到结尾的文件内容。
我该怎么做?
【问题讨论】: