1.读取txt文件
// 读取txt文件(文件中的数据以空格为间隔)
bool read_txt(const std::string& file_path) {
std::ifstream infile;
infile.open(file_path); // 将文件流对象与文件关联起来,默认以只读方式打开std::ios::in
if (!infile.is_open()) {
return false;
}
std::vector<std::vector<double>> path_points;
std::string line, x, y, s, heading, kappa;
while (getline(infile, line)) { // 读取一行
std::stringstream words(
line); // 创建字符串流对象,然后将每个words写入到字符串变量中
words >> x;
words >> y;
words >> s;
words >> heading;
words >> kappa;
double pt_x = std::atof(x.c_str()); // 将字符串转换为float
double pt_y = std::atof(y.c_str());
double pt_s = std::atof(s.c_str());
double pt_heading = std::atof(heading.c_str());
double pt_kappa = std::atof(kappa.c_str());
path_points.push_back({pt_x, pt_y, pt_s, pt_heading, pt_kappa});
}
infile.close();
}
2.写入内容
以std::ios::out方式打开,如果文件不存在,则会创建
void write_txt(const std::string& file_path) {
std::ofstream out_file;
out_file.open(file_path, std::ios::out);
if(out_file.is_open()){
//输入标题行
out_file<<"x"<<' '<<"y"<<' '<<"z"<<std::endl;
out_file.close(); //关闭文件
}else{
std::cout<<"文件打开失败\n";
}
}
3.追加内容
以std::ios::app方式打开,进行追加,若文件不存在则会创建
void app_txt(const std::string& file_path) {
std::ofstream out_file;
out_file.open(file_path, std::ios::app);
if (out_file.is_open()) {
//
out_file << std::to_string(0) << ' ' << std::to_string(1) << ' '
<< std::to_string(2) << ' ' << std::to_string(1) << ' '
<< std::to_string(1) <<std::endl;
out_file.close(); // 关闭文件
} else {
std::cout << "文件打开失败\n";
}
}