Read and write files in binary files can be used QFile class, QStream
read and write text files is recommended QTextStream class that manipulates files more convenient.
When you open a file, you need to open the file parameter specifies the mode:
mode | value | description |
QIODevice :: NotOpen | 0x0000 | Do not open |
QIODevice::ReadOnly | 0x0001 | Read-only |
QIODevice::WriteOnly | 0x0002 | Write-only mode, if the file does not exist it will automatically create a file |
QIODevice::ReadWrite | ReadOnly | WriteOnly | Reading and writing |
QIODevice::Append | 0x0004 | This pattern indicates that all data written to the end of the file |
QIODevice::Truncate | 0x0008 | Before opening a file, the file is truncated, all data will be lost original file |
QIODevice::Text | 0x0010 | Read, end of file flag will be converted to '\ n'; the time of writing, end of file flag will be turned end for local encoding, such as the end of the bit win32 '\ r \ n' |
QIODevice::UnBuffered | 0x0020 | Do not cache |
QIODevice :: Text used when reading and writing a text file, so that line breaks can be automatically converted to local newline.
(1) written to a text file
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();
Write the contents of the file as:
123
123
(2) read a text file
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的流操作符