写一个c++代码,将一个文件夹里的文件名字全部提取到txt文档中
时间: 2023-02-26 11:18:35 浏览: 58
以下是一个示例代码,它将文件夹中的文件名称全部提取到txt文档中:
```c
#include <dirent.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *ent;
if ((dir = opendir(".")) != NULL) {
/* 打开当前目录 */
FILE *fp;
fp = fopen("filenames.txt", "w");
/* 以写入模式打开文件 */
while ((ent = readdir(dir)) != NULL) {
/* 读取目录中的每一个文件 */
fprintf(fp, "%s\n", ent->d_name);
/* 将文件名写入文件 */
}
closedir(dir);
fclose(fp);
/* 关闭文件 */
} else {
/* 打开目录失败 */
perror("");
return 1;
}
return 0;
}
```
这段代码使用了dirent库函数来读取目录中的文件,并使用标准文件I/O函数fopen和fprintf来写入文件。请注意,此代码仅在当前目录中提取文件名称,如果要提取其他目录中的文件名称,可以将目录名称作为第一个参数传递给opendir。
相关问题
C++写一个将数据包保存到txt文件的代码
可以使用以下代码将数据包保存到txt文件中:
```c
#include <stdio.h>
int main() {
char data[] = "这是要保存的数据包内容";
FILE *fp;
fp = fopen("data.txt", "w");
fprintf(fp, "%s", data);
fclose(fp);
return ;
}
```
这段代码中,我们首先定义了一个字符串变量 `data`,用于存储要保存的数据包内容。然后使用 `fopen` 函数打开一个名为 `data.txt` 的文件,并以写入模式打开。接着使用 `fprintf` 函数将数据包内容写入文件中,最后使用 `fclose` 函数关闭文件。这样就可以将数据包保存到txt文件中了。
用c++写一个将文件夹中的txt文件转为pcd格式
以下是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`替换为要转换的文件夹路径。