QT在進行文本讀寫時和C++一樣,是基於文本流操作的。
QT在讀取全部文本時,相對比較便捷。使用readAll()函數,配合split()進行分隔符的拆分(例如行結束符"\n"),可將拆分結果賦值給list,然后進行后續的數據處理。
ringRoadDistList = ringRoadDistStream.readAll().split("\n",QString::SkipEmptyParts);
在C++中也可以實現類似的效果:
list<string> strList; char line[100]; while (false == staEnLane2Stream.eof()) { staEnLane2Stream.getline(line, sizeof(line)); //c從staEnLane2Stream按行讀取sizeof(line)個數到緩沖區line中(遇到"\n",將提前截止) strList.push_back(line); }
如果遇到換行符'\n'(第一種形式)或delim(第二種形式),則讀取終止,'\n'或delim都不會被保存進s對應的數組中。
基於文本流的輸出,兩個類似:
ofstream resultStream; resultStream.open(staEnLane3Path.c_str(), ios_base::out); if (false == resultStream.is_open()) { cerr << "error: unable to open output file: " << staEnLane3Path << endl; return 2; } while (lane2Map.end() != j) { cout << (*j).first << " " << (*j).second << endl; resultStream << (*j).first << " " << (*j).second << endl; ++j; }
舉個栗子:
// ringRoadTime.cpp : 定義控制台應用程序的入口點。 #include "stdafx.h" #include <string> #include <cstring> #include <cstdlib> #include <fstream> #include <iostream> #include <list> #include <map> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { string rootPath = "E:/superHighway/ringRoadData/GC/GC_Entry/"; string staEnLane2Name = "GC_stationEntryLane2.csv"; string staEnLane3Name = "GC_stationEntryLane.csv"; string staEnLane2Path = rootPath + staEnLane2Name; string staEnLane3Path = rootPath + staEnLane3Name; //ifstream staEnLane2Stream(staEnLane2Path.c_str(), ios::in); ifstream staEnLane2Stream; ofstream resultStream; //文件打開,保存數據到list,關閉文件 staEnLane2Stream.open(staEnLane2Path.c_str(), ios_base::in); if (false == staEnLane2Stream.is_open()) { cerr << "error: unable to open input file: " << staEnLane2Path << endl; return 1; } list<string> strList; char line[100]; while (false == staEnLane2Stream.eof()) { staEnLane2Stream.getline(line, sizeof(line)); strList.push_back(line); } staEnLane2Stream.close(); resultStream.open(staEnLane3Path.c_str(), ios_base::out); if (false == resultStream.is_open()) { cerr << "error: unable to open output file: " << staEnLane3Path << endl; return 2; } //數據插入map中,進行匹配 map<string, string> lane2Map; list<string>::iterator k = strList.begin(); for (; k != strList.end(); ++k) { size_t i = (*k).find_first_of(","); lane2Map.insert(pair<string, string>((*k).substr(0,i), (*k).substr(i+1))); } map<string, string>::iterator j = lane2Map.begin(); while (lane2Map.end() != j) { cout << (*j).first << " " << (*j).second << endl; resultStream << (*j).first << " " << (*j).second << endl; //基於文本流的數據寫入 ++j; } resultStream.close(); system("pause"); return 0; }
