我的 txt 檔案 (CopyBook.txt) 包含例如 10 行。我想洗掉第三個。
我有這個代碼:
QString fname = "C://Users//Tomahawk//Desktop//copy//CopyBook.txt";
QFile file(fname);
if (file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append))
{
QTextStream edit(&file);
QString line;
int reachForLine = 0;
int neededLine = 3;
while (reachForPage != pageCounter)
{
line = edit.readLine();
reachForPage ;
}
}
所以你可以看到我使用“while”來到達我想要洗掉的行。但是我還沒有在 Qt 中找到任何允許我這樣做的方法。將來我想使用洗掉行的功能將它們替換為其他行。那么如何洗掉呢?
uj5u.com熱心網友回復:
一種方法是將所有行讀入 a QStringList,修改QStringList,然后再次將其內容寫回檔案,如下所示:
int main(int argc, char ** argv)
{
const QString fname = "C:/Users/Tomahawk/Desktop/copy/CopyBook.txt";
QStringList lines;
// Read lines of text from the file into the QStringList
{
QFile inputFile(fname);
if (inputFile.open(QIODevice::ReadOnly | QIODevice::Text))
{
QTextStream edit(&inputFile);
while (!edit.atEnd()) lines.push_back(edit.readLine());
}
inputFile.close();
}
// Delete the third line from the QStringList
if (lines.length() > 2) lines.removeAt(2); // 0==first line, 1==second line, etc
// Write the text in the QStringList back to the file
{
QFile outputFile(fname);
if (outputFile.open(QIODevice::WriteOnly | QIODevice::Text))
{
QTextStream edit(&outputFile);
for (int i=0; i<lines.size(); i ) edit << lines[i] << Qt::endl;
}
outputFile.close();
}
return 0;
}
在將QStringList物件寫回檔案之前,您還可以對物件執行任何替換/插入操作。
請注意,這種方法確實會使用與檔案大小成正比的 RAM,因此對于非常大的檔案(例如千兆位元組長),您可能希望使用 @ 提出的創建第二個檔案然后重命名的方法相反,TedLyngmo 在他的評論中。對于小檔案 OTOH,在 RAM 中緩沖更容易且不易出錯。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/359396.html
