參考:http://blog.csdn.net/xgbing/article/details/7772953
二進制文件的讀寫文件可以使用QFile類、QStream
文本文件的讀寫建議使用QTextStream類,它操作文件更加方便。
打開文件時,需要參數指定打開文件的模式:
| 模式 | 值 | 描述 |
| 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 | 不緩存 |
QIODevice::Text在讀寫文本文件時使用,這樣可以自動轉化換行符為本地換行符。
(1)寫入文本文件
QFile f("c:\\test.txt"); if(!f.open(QIODevice::WriteOnly | QIODevice::Text)) { cout << "Open failed." << endl; return -1; } QTextStream txtOutput(&f); QString s1("123"); quint32 n1(123); txtOutput << s1 << endl; txtOutput << n1 << endl; f.close();
寫入的文件內容為:
123
123
(2)讀取文本文件
QFile f("c:\\test.txt"); if(!f.open(QIODevice::ReadOnly | QIODevice::Text)) { cout << "Open failed." << endl; return -1; } QTextStream txtInput(&f); QString lineStr; while(!txtInput.atEnd()) { lineStr = txtInput.readLine(); cout << lineStr << endl; } f.close();
屏幕打印的內容為:
123
123
QTextStream的流操作符

轉自:https://blog.csdn.net/zong596568821xp/article/details/78920243
