qt读写一个文件的操作

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lvdepeng123/article/details/81060917

参考: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 不缓存
虽然QT使用C++,当然也可以使用fstream。但是学会用QT封装好了的API会大幅度提高效率。(可以用带缓存的I/O操作,fopen,fread,fwrite)

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. QTextStream txtOutput(&f);
  8. QString s1("123");
  9. quint32 n1(123);
  10. txtOutput << s1 << endl;
  11. txtOutput << n1 << endl;
  12. 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. QTextStream txtInput(&f);
  8. QString lineStr;
  9. while(!txtInput.atEnd())
  10. {
  11. lineStr = txtInput.readLine();
  12. cout << lineStr << endl;
  13. }
  14. f.close();
屏幕打印的内容为:
123

123

QTextStream的流操作符

个人分类:  Qt

参考: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 不缓存
虽然QT使用C++,当然也可以使用fstream。但是学会用QT封装好了的API会大幅度提高效率。(可以用带缓存的I/O操作,fopen,fread,fwrite)

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. QTextStream txtOutput(&f);
  8. QString s1("123");
  9. quint32 n1(123);
  10. txtOutput << s1 << endl;
  11. txtOutput << n1 << endl;
  12. 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. QTextStream txtInput(&f);
  8. QString lineStr;
  9. while(!txtInput.atEnd())
  10. {
  11. lineStr = txtInput.readLine();
  12. cout << lineStr << endl;
  13. }
  14. f.close();
屏幕打印的内容为:
123

123

QTextStream的流操作符

猜你喜欢

转载自blog.csdn.net/lvdepeng123/article/details/81060917