Qt入门-文件读写

转自:http://blog.csdn.net/xgbing/article/details/7772953  非常感谢原作者!


二进制文件的读写文件可以使用QFile类、QStream

文本文件的读写建议使用QTextStream类,它操作文件更加方便。

打开文件时,需要参数指定打开文件的模式:

[plain]  view plain copy
  1. Constant        Value   Description  
  2. QIODevice::NotOpen  0x0000  The device is not open.  
  3. QIODevice::ReadOnly 0x0001  The device is open for reading.  
  4. QIODevice::WriteOnly    0x0002  The device is open for writing.  
  5. QIODevice::ReadWrite    ReadOnly | WriteOnly    The device is open for reading and writing.  
  6. QIODevice::Append   0x0004  The device is opened in append mode, so that all data is written to the end of the file.  
  7. QIODevice::Truncate 0x0008  If possible, the device is truncated before it is opened. All earlier contents of the device are lost.  
  8. QIODevice::Text 0x0010  When reading, the end-of-line terminators are translated to '\n'. When writing, the end-of-line terminators are translated to the local encoding, for example '\r\n' for Win32.  
  9. QIODevice::Unbuffered   0x0020  Any buffer in the device is bypassed.  

QIODevice::Text在读写文本文件时使用,这样可以自动转化换行符为本地换行符。



(1)写入文本文件

[cpp]  view plain copy
  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)读取文本文件

[cpp]  view plain copy
  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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值