用c++写一个将文件夹中的txt文件转为pcd格式
时间: 2024-02-27 20:56:16 浏览: 21
以下是C++实现的将文件夹中的txt文件转换为pcd格式的代码示例:
```cpp
#include <iostream>
#include <string>
#include <vector>
#include <filesystem> // C++17标准的文件系统库,需要编译器支持
int txt_to_pcd(const std::string& txt_file, const std::string& pcd_file)
{
std::string cmd = "pcl_txt2pcd " + txt_file + " " + pcd_file;
int ret = std::system(cmd.c_str());
return ret;
}
void batch_txt_to_pcd(const std::string& folder_path)
{
// 创建输出文件夹
std::string pcd_folder = folder_path + "/pcd_files";
if (!std::filesystem::exists(pcd_folder)) {
std::filesystem::create_directory(pcd_folder);
}
// 遍历文件夹中的txt文件,逐个转换为pcd文件
for (const auto& entry : std::filesystem::directory_iterator(folder_path)) {
if (entry.path().extension() == ".txt") {
std::string txt_file = entry.path().string();
std::string pcd_file = pcd_folder + "/" + entry.path().stem().string() + ".pcd";
int ret = txt_to_pcd(txt_file, pcd_file);
if (ret == 0) {
std::cout << txt_file << " 转换为 " << pcd_file << " 完成!" << std::endl;
} else {
std::cerr << txt_file << " 转换失败!" << std::endl;
}
}
}
}
// 测试
int main()
{
std::string folder_path = "/path/to/folder";
batch_txt_to_pcd(folder_path);
return 0;
}
```
将上述代码保存为C++源代码文件,然后使用支持C++17标准的编译器编译并运行即可批量将文件夹中的txt文件转换为pcd文件,并保存在与txt文件相同的文件夹中的`pcd_files`子文件夹中。注意,需要将`/path/to/folder`替换为要转换的文件夹路径。