在讀取大容量數據的時候,前面的幾行常常包括文件的說明,所以讀取的時候應該去掉,而且我們經常需要讀取文件中的指定列的數據。下面的例子演示了這個功能:
//定位到txt文件的某一行
ifstream & seek_to_line(ifstream & in, int line)
//將打開的文件in,定位到line行。
{
int i;
char buf[1024];
in.seekg(0, ios::beg); //定位到文件開始。
for (i = 0; i < line; i++)
{
in.getline(buf, sizeof(buf));//讀取行。
}
return in;
}
int _tmain(int argc, _TCHAR* argv[])
{
//讀取文件路徑
std::string pts_filename = "E:/數據文件/20190718.txt";
std::vector<Point3D> pts;
{
std::ifstream pts_file;
pts_file.open(pts_filename);
seek_to_line(pts_file, 2); //定位到指定的行開始讀取
if (!pts_file.is_open())
{
cout << "Unable to open myfile";
system("pause");
exit(1);
}
while (!pts_file.eof())
{
//先忽略前面的2列,從第三列開始讀取,讀取了3-5列x,y,z的數據保存到point3D中,然後
//當前行後面的數據全部忽略
for (Point3D pt; (((pts_file >> ws).ignore(numeric_limits<streamsize>::max(), ' ') >> ws).ignore(numeric_limits<streamsize>::max(), ' ') >> pt.x >> pt.y >> pt.z >> ws).ignore(numeric_limits<streamsize>::max(), '\n');)
{
pts.push_back(pt); //將數據保存下來
}
}
pts_file.close();
}
return 0;
}
由於後來需要用到一些windows的函數,出現了編譯錯誤,參考了鏈接:https://blog.csdn.net/huixingshao/article/details/86534865。std::numeric_limits::max()使用的是STL中的z數值極限<Numeric Limits>,如果又添加了#include<windows.h>則會出現如下錯誤:
warning C4003: “max”宏的實參不足
error C2589: “(” : “::”右邊的非法標記
因爲需要把max用括號括起來避免和windows定義的宏混淆
(std::numeric_limits<double>::max)()
因爲Windef.h中定義了
#ifndef max
#define max(a,b) (((a) > (b)) ? (a) : (b))
#endif
所以會產生編譯錯誤。