QT在进行文本读写时和C++一样,是基于文本流操作的。
QT在读取全部文本时,相对比较便捷。使用readAll()函数,配合split()进行分隔符的拆分(例如行结束符" "),可将拆分结果赋值给list,然后进行后续的数据处理。
ringRoadDistList = ringRoadDistStream.readAll().split(" ",QString::SkipEmptyParts);
在C++中也可以实现类似的效果:
list<string> strList; char line[100]; while (false == staEnLane2Stream.eof()) { staEnLane2Stream.getline(line, sizeof(line)); //c从staEnLane2Stream按行读取sizeof(line)个数到缓冲区line中(遇到" ",将提前截止) strList.push_back(line); }
如果遇到换行符' '(第一种形式)或delim(第二种形式),则读取终止,' '或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; }