Qt寫入讀取txt文本文件

打開文件時,使用參數選擇打開文件模式

模式 描述
QIODevice::NotOpen 0x0000 不打開
QIODevice::ReadOnly 0x0001 只讀方式
QIODevice::WriteOnly 0x0002 只寫方式,如果文件不存在則會自動創建文件
QIODevice::ReadWrite ReadOnly WriteOnly
QIODevice::Append 0x0004 此模式表明所有數據寫入到文件尾
QIODevice::Truncate 0x0008 打開文件之前,此文件被截斷,原來文件的所有數據會丟失
QIODevice::Text 0x0010 讀的時候,文件結束標誌位會被轉爲’\n’;寫的時候,文件結束標誌位會被轉爲本地編碼的結束爲,例如win32的結束位’\r\n’
QIODevice::UnBuffered 0x0020 不緩存

需要導入QFile和qDebug、QString頭文件

寫入

覆蓋寫入

QFile f("D:\\qtManager.txt");
if(!f.open(QIODevice::WriteOnly | QIODevice::Text))
{
    qDebug() << ("打開文件失敗");
}
QTextStream txtOutput(&f);
QString str = "123";
txtOutput << str << endl;
f.close();

文末寫入

QFile f("D:\\qtManager.txt");
if(!f.open(QIODevice::ReadWrite | QIODevice::Append))   //以讀寫且追加的方式寫入文本
{
    qDebug() << ("打開文件失敗");
}
QTextStream txtOutput(&f);
QString str = "123";
txtOutput << str << endl;
f.close();

讀取

QFile f("D:\\qtManager.txt");
if(!f.open(QIODevice::ReadOnly | QIODevice::Text))
{
    qDebug() << ("打開文件失敗");
}
QTextStream txtInput(&f);                 
QString lineStr;
while(!txtInput.atEnd())
{
    lineStr = txtInput.readLine();
    qDebug() << (lineStr);
}
f.close();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章