二進制文件的讀寫文件可以使用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)寫入文本文件
1 QFile f("c:\\test.txt"); 2 if(!f.open(QIODevice::WriteOnly | QIODevice::Text)) 3 { 4 cout << "Open failed." << endl; 5 return -1; 6 } 7
8 QTextStream txtOutput(&f); 9 QString s1("123"); 10 quint32 n1(123); 11
12 txtOutput << s1 << endl; 13 txtOutput << n1 << endl; 14
15 f.close();
寫入的文件內容為:
123
123
(2)讀取文本文件
1 QFile f("c:\\test.txt"); 2 if(!f.open(QIODevice::ReadOnly | QIODevice::Text)) 3 { 4 cout << "Open failed." << endl; 5 return -1; 6 } 7
8 QTextStream txtInput(&f); 9 QString lineStr; 10 while(!txtInput.atEnd()) 11 { 12 lineStr = txtInput.readLine(); 13 cout << lineStr << endl; 14 } 15
16 f.close();
屏幕打印的內容為:
123
123
123
QTextStream的流操作符

