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();
posted @   半夜打老虎  阅读(665)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示