Qt使用Qtextstream進行換行操作

使用QTextStream向txt文件輸出換行時,需要使用QIODevice::Text標誌。

官方文檔對QIODevice::Text的解釋:

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.

簡而言之,該標誌指示在讀寫過程中要對end-of-line進行轉換。


例子

(1)不使用QIODevice::Text

  1. #include <QCoreApplication>  
  2. #include <QFile>  
  3. #include <QTextStream>  
  4.   
  5. int main(int argc, char *argv[])  
  6. {  
  7.     QCoreApplication a(argc, argv);  
  8.     QFile file("C:/Users/Administrator/Desktop/1.txt");  
  9.     if (file.open(QIODevice::WriteOnly))  
  10.     {  
  11.         QTextStream out(&file);  
  12.         out << endl << '*';  
  13.     }  
  14.     return a.exec();  
  15. }  


輸出:

可見輸出換行達不到效果。


(2)不使用QIODevice::Text

  1. #include <QCoreApplication>  
  2. #include <QFile>  
  3. #include <QTextStream>  
  4.   
  5. int main(int argc, char *argv[])  
  6. {  
  7.     QCoreApplication a(argc, argv);  
  8.     QFile file("C:/Users/Administrator/Desktop/1.txt");  
  9.     if (file.open(QIODevice::Text | QIODevice::WriteOnly))  
  10.     {  
  11.         QTextStream out(&file);  
  12.         out << endl << '*';  
  13.     }  
  14.     return a.exec();  
  15. }  


效果:


轉自:http://blog.csdn.net/u012689588/article/details/19431353

發佈了36 篇原創文章 · 獲贊 32 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章