我有一個基本問題:
我以只讀模式打開一個舊日志檔案并將內容存盤在 QTextStream 中,然后將其關閉。它基本上包含 7 行文本。
我打開另一個檔案寫入并嘗試逐行讀取。我可以逐行讀取并將全部內容寫入新檔案。但我正在嘗試執行以下操作:
將前 5 行按原樣寫入新檔案,對第 6 行和第 7 行做一些更改并寫入新行
QString oldfilename = "log_file";
QString newfilename = "new_log_file";
QString path1 = QCoreApplication::applicationDirPath() "/" oldfilename ".txt";
QString path2 = QCoreApplication::applicationDirPath() "/" newfilename ".txt";
QFile readfile(path1);
if(!readfile.open(QIODevice::ReadOnly | QIODevice::Text)){
qDebug() << "Error opening file: "<<readfile.errorString();
}
QTextStream instream(& readfile);
QFile writefile(path2);
if(file.open(QIODevice::WriteOnly | QIODevice::Text))
{
int nb_line(0);
while(!instream.atEnd())
{
QString line = instream.readLine();
// Here I need to write first five lines of the file as it is
if(nb_line == 6 )
{
// Do some manipulation here
outstream <line_6<< '\n'
}
if(nb_line == 7 )
{
// Do some manipulation here
outstream <line_7<< '\n'
}
nb_line;
}
readfile.close();
writefile.close();
}
有人可以建議一種有效的方法(使用回圈)按原樣選擇第一行并管理對第 6 行和第 7 行的更改
我可以將整個內容逐行寫入新檔案,但不確定如何使用正確的回圈來選擇
例如,如果舊檔案的內容是
Apple
Cherry
Pineapple
Pear
Grape
Mushroom
Egg
我需要我的新檔案:
Apple
Cherry
Pineapple
Pear
Grape
Orange
Watermelone
uj5u.com熱心網友回復:
因為它是 5 行,所以你可以撰寫一個簡單的 while 回圈(我正在使用 fstream 庫)
void readFirstFiveLines() {
std::ifstream file("file.txt");
std::ofstream file2("file2.txt");
std::string line;
int i = 0;
while (std::getline(file, line) && i < 5) {
file2 << line << std::endl;
i ;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/534444.html
標籤:C qt
上一篇:錯誤:“SkipEmptyParts”不是“Qt”的成員
下一篇:訪問另一個用戶的git倉庫
