【问题标题】:C++ - List files of directory and save output result on txtC ++ - 列出目录文件并将输出结果保存在txt中
【发布时间】:2021-01-13 11:00:38
【问题描述】:

我需要将此代码的结果输出到 txt。当我尝试时它只保存一行。


using namespace std;
std::string c;

void list_dir(const char *path) {
struct dirent *entry;
DIR *dir = opendir(path);
if (dir == NULL) {
   return;
}
while ((entry = readdir(dir)) != NULL) {
c = entry->d_name;
cout << c << endl;
}
closedir(dir);
}

谢谢

【问题讨论】:

  • 输出是什么,你期望什么输出?
  • 我看到您正在使用 POSIX 的文件系统 API。您是否考虑过改用 C++ 标准文件系统库?
  • "当我尝试时它只保存一行。" - 你的程序不会“保存”任何东西 - 它只调用puts 打印到stdout。我想这就是你的意思?
  • 请将您的问题集中在实现多行或将输出放入文件中。
  • 请将显示的代码片段升级为minimal reproducible example

标签: c++ list file


【解决方案1】:

使用文件系统标头。 例如:

#include <fstream>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
 
int main()
{
    std::fstream fs("Output.txt")
    fs::current_path(fs::temp_directory_path());
    fs::create_directories("sandbox/a/b");
    std::ofstream("sandbox/file1.txt");
    fs::create_symlink("a", "sandbox/syma");
    for(auto& p: fs::recursive_directory_iterator("sandbox"))
        fs.write(p.path());

    
    fs::remove_all("sandbox");
}

这将创建并返回目录中的所有文件

【讨论】:

  • 我没有得到 OP 要求创建的印象......而且我对“创建目录中的所有文件”感到困惑,或者文件存在(然后它不需要创建)或不存在(那么它不在“全部”之中,为什么要创建它)。
  • 我找不到你
  • “这会创建(... snip ...)目录中的所有文件”让我感到困惑,因为我没有得到 OP 询问有关创建文件的印象。
猜你喜欢
  • 1970-01-01
  • 2014-12-29
  • 2014-11-16
  • 1970-01-01
  • 2023-02-01
  • 1970-01-01
  • 2021-06-28
  • 2018-06-20
  • 1970-01-01
相关资源
最近更新 更多