[英]QT, Write in new line in a file
我編寫了一個代碼,以從GUI中的line_Edit讀取並寫入文件。 代碼從行編輯中讀取文本並將其寫入文件,但是它們連續打印而沒有任何空格,我想在不同行中打印在行編輯中寫入的文本。 該文件具有書面文字,只想由用戶輸入的單詞替換每行的第一個單詞。
寫入文件的代碼:
void MainWindow::on_write_btn_clicked(){
QString str, str2, lin;
str = ui->lineEdit->text();
str2 = ui->lineEdit2->text();
QFile file1("sample.txt");
if(file1.open(QIODevice::ReadWrite | QIODevice::Text)){
QTextStream out(&file1);
out << str;
lin = out.readLine();
out << str2;
file1.seek(30);
file1.close();
}
else
return;
}
如果希望下一個字符串在文件的新行中,則應將新行字符添加到流\\n
。 參考您的代碼,您應該輸入:
out << str << '\n' << str2;
這將使str
和str2
的內容顯示在連續的行中。
除了上述內容,您還可以使用QTextStream
的endl
操縱器:
out << str << endl << str2;
為了QIODevice::Text
正常工作,您需要使用QIODevice::Text
打開文件,並確保您指定的endl
實際上來自QTextStream
(而不是std
)。另外請注意,由於您可能只想編寫文件,因此不需要用ReadWrite
選項打開它, WriteOnly
應該足夠了。
根據更多詳細信息進行編輯 :
要替換文件每一行中的第一個單詞,您可以執行以下操作。 打開兩個文件,一個將被讀取,第二個將寫入修改后的數據。 遍歷所有行關閉文件后,請刪除原始文件,然后重命名輸出文件以替換原始文件。 實施示例:
QFile fileIn("textIn.txt"), fileOut("textOut.txt");
fileIn.open(QFile::ReadOnly); // check result
fileOut.open(QFile::WriteOnly); // check result
QTextStream streamIn(&fileIn), streamOut(&fileOut);
const QChar delimeter = ' ';
while (!streamIn.atEnd())
{
QStringList list = streamIn.readLine().split(delimeter);
if (list.size() > 0) // in case of empty line
list[0] = "substitutedText"; // here put the text you want to set
streamOut << list.join(delimeter) << "\r\n"; // or endl
}
fileIn.close();
fileOut.close();
fileIn.remove(); // check result
fileOut.rename(QFileInfo(fileIn).absoluteFilePath()); // check result
當然,您可以嘗試對使用ReadWrite
修飾符打開的原始文件進行替換,並使用seek
在流中設置適當的位置。 盡管由於讀取和寫入數據的長度不同,它可能會變得棘手。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.