C++文件操作

旧城冷巷雨未停 提交于 2020-01-15 07:27:03

最近经常用来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;
    }
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!