假设我有一个包含10行的文本文件。我想转到第5行,清除它下面的所有内容,然后添加一些新文本。使用C ++流来实现这一目标的最紧凑的方法是什么(以防万一我错过了一些流功能)?
答案 0 :(得分:3)
在写入第二个文件时读取N行,然后将所有新文本写入新文件。
答案 1 :(得分:2)
使用IOstream打开文件并将前五行存储在一个数组中,并使用数组和您想要的任何其他行重新创建测试文件。这是一个代码示例:
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
const int linesToRead = 5; //How many lines to read before stopping
string lines [linesToRead];
int line = 0;
ifstream myinputfile ("example.txt");
if (myinputfile.is_open())
{
while ( myinputfile.good() && line<=linesToRead )
{
if(line<linesToRead)
{ //Stop reading at line 5
getline (myinputfile,lines[line]);
cout << lines[line];
}
line++;
}
myinputfile.close();
}
else cout << "Unable to open file";
//Begin creating new file
const int numberOfNewLines = 7;
string newlines[numberOfNewLines] = {"These", "are", "some", "of", "the", "new", "lines"}; //lines to be added after the previous 5
ofstream myoutputfile ("example.txt");
if (myoutputfile.is_open())
{
for(int i = 0; i<linesToRead; i++){
myoutputfile << lines[i] << "\n";
}
for(int i = 0; i<numberOfNewLines; i++){
myoutputfile << newlines[i] << "\n";
}
myoutputfile.close();
}
else cout << "Unable to open file";
return 0;
}