-1
假設我有一個包含10行的文本文件。我想移動到第5行,清除它下面的所有內容,然後添加一些新的文本。什麼是最簡潔的方法來實現這個使用C++的流(以防萬一我錯過了一些流功能)?如何在特定行號後添加文本?
假設我有一個包含10行的文本文件。我想移動到第5行,清除它下面的所有內容,然後添加一些新的文本。什麼是最簡潔的方法來實現這個使用C++的流(以防萬一我錯過了一些流功能)?如何在特定行號後添加文本?
在寫入第二個文件時讀取N行,然後將所有新文本寫入新文件。
使用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;
}
您是否想要覆蓋第5行後面的行,或者直接插入它們,然後再推回下一行? –
看看這個答案,它會解釋很多:http://stackoverflow.com/questions/6154618/delete-a-line-in-an-ofstream-in-c – Amadeus