天天看點

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();
           

繼續閱讀