zoukankan      html  css  js  c++  java
  • C++读写文本文件

    文件内容

    读取文件

    • 先打开文件,按行读取
    • 对每行数据按空格分割
    • 格式转换
    #include <iostream>
    #include <memory>
    #include <vector>
    #include <fstream>
    #include <sstream>
    
    void preprocess(std::string dataPath) {
    	std::fstream infile;
    	infile.open(dataPath, std::ios::in);   // 打开文件
    	if (!infile.is_open()) {
    		std::cout << "open file " << dataPath << " failed! " << std::endl;
    		return;
    	}
    	std::vector<std::string> data;
    	std::string s;
    	while (std::getline(infile, s)) {     // 按行读取
    		data.push_back(s);
    	}
    
    	std::vector<std::vector<float> > points;
    	std::string suffix = dataPath.substr(dataPath.find_last_of('.') + 1);   // 获取文件类型
    	if (suffix == "txt") {
    		for (int i = 0; i < data.size(); ++i) {
    			std::vector<float> line_data;
    			std::istringstream ss(data[i]);
    			std::string item;
    			int n = 0;
    			while (n <3 && ss >> item) {                           // 按空格分割并对相应数据进行格式转换
    				line_data.push_back(std::stof(item));
    				n += 1;
    			}
    			points.push_back(line_data);
    		}
    	}
    	else if (suffix == "pcd"){
    		int skipRows = 10;
    		for (int i = skipRows; i < data.size(); ++i) {
    			std::vector<float> line_data;
    			std::istringstream ss(data[i]);
    			std::string item;
    			int n = 0;
    			while (n <3 && ss >> item) {
    				line_data.push_back(std::stof(item));
    				n += 1;
    			}
    			points.push_back(line_data);
    		}
    	}
    	else {
    		std::cout << "Don't support file type, just useful for txt or pcd!";
    		return;
    	}
    }
    

    写入文件

    std::vector<std::vector<float> >resPts;
    std::fstream outfile;
    outfile.open("D:/Debug_dir/res.pts", std::ios::out);
    if (!outfile.is_open()) {
        std::cout << "write res to file is failed! " << std::endl;
        return false;
    }
    for (auto pt : resPts) {
        outfile << pt[0] << " " << pt[1] << " " << pt[2] << "\n";
    }
    outfile.close();
    
  • 相关阅读:
    “能用”距离“好用”有多远?
    序列化到底是神马?
    新版Microsoft Azure Web管理控制台
    玩转Windows Azure存储服务——高级存储
    Windows 10 Threshold 2 升级记录
    玩转Windows Azure存储服务——网盘
    Windows Azure HDInsight 使用技巧
    Docker on Microsoft Azure
    Azure Linux VM Swap 分区
    Google Cloud Platform
  • 原文地址:https://www.cnblogs.com/xiaxuexiaoab/p/15566375.html
Copyright © 2011-2022 走看看