最近经常用来C++读取或者保存txt文件,特此记录一下操作,以便之后查询:
1.打开一个文件
std::ifstream f;
f.open("bin/house_model/house.txt");
if (!f)
cout << "not open the house.txt"<<endl;
按行读取该文件:
while(!f.eof())
{
std::string s;
std::getline(f,s);
if(!s.empty())
{
std::stringstream ss;
ss << s;
double x,y,z;
ss >> x;
ss >> y;
ss >> z;
Eigen::Vector4d pt0( x, y, z, 1 );
ss >> x;
ss >> y;
ss >> z;
Eigen::Vector4d pt1( x, y, z, 1 );
}
}
先判断是不是到文件末尾了,然后把读取到的一行,给一个文件流ss,该文件流可以按个数进行赋值。
2.保存文件
void save_points(std::string filename, std::vector<Eigen::Vector4d, Eigen::aligned_allocator<Eigen::Vector4d> > points)
{
std::ofstream save_points;
save_points.open(filename.c_str());
for (int i = 0; i < points.size(); ++i) {
Eigen::Vector4d p = points[i];
save_points<<p(0)<<" "
<<p(1)<<" "
<<p(2)<<" "
<<p(3)<<std::endl;
}
}
来源:CSDN
作者:remanented
链接:https://blog.csdn.net/remanented/article/details/103742714