文件内容

读取文件
- 先打开文件,按行读取
- 对每行数据按空格分割
- 格式转换
#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();