【问题标题】:Opening a directory in c++在 C++ 中打开一个目录
【发布时间】:2017-07-25 17:11:43
【问题描述】:

我正在尝试编写一个程序,将文件从一个目录移动到另一个目录,到目前为止我已经写好了。

void file_Move(ifstream in,ofstream out)
{
    string name, name2; 
    int downloads;

    cout << "Enter 1 if the file you wish to move is in downloads" << endl;
    cin >> downloads;

        if (downloads == 1)
        {
            opendir("F:/Downloads"); //supposed to open the directory so that the user can input the file they wish to be moved.
            closedir("F:/Downloads");
        }
}

Visual Studio 没有 opendir 和 closedir 所必需的 dirent.h 库,所以我想知道是否有类似或更好的方法来执行这些操作。

【问题讨论】:

  • 处理目录需要特定于操作系统的函数,它不是 C++ 规范的一部分。
  • 如果您询问的是 Win32 API,请在 MSDN 上查找 FindFirstFile 和 FindNextFile 以及相关函数。
  • @Barmar:实际上,它委员会最近批准的即将正式发布的规范的一部分。
  • 实际上,它是即将正式发布的规范的一部分 ...最后,不敢相信他们花了这么长时间。如果你不能等到 C++17,还有boost::filesystem::rename

标签: c++ stream directory move


【解决方案1】:

就目前而言,您的代码没有多大意义。

一方面,file_move 采用 ifstream 和 ofstream,这意味着您已经找到并打开了您关心的文件。然后它继续尝试搜索文件...

目前,我假设您需要搜索您关心的文件。在这种情况下,您可能想要使用 filesystem 库。使用真正最新的编译器,这可能直接在std:: 中。对于稍旧的编译器,它可能位于std::experimental。对于更旧的版本(早于文件系统 TS),您可能需要改用 Boost Filesystem

在任何情况下,使用它的代码都会像这样运行:

#include <string>
#include <filesystem>
#include <iostream>
#include <iterator>
#include <algorithm>

void show_files(std::string const & path) {
    // change to the std or Boost variant as needed.
    namespace fs = std::experimental::filesystem::v1;

    fs::path p{ path };

    fs::directory_iterator b{ p }, e;

    std::transform(b, e, 
        std::ostream_iterator<std::string>(std::cout, "\n"), 
        [](fs::path const &p) {
            return p.string();
        }
    );
}

当然,如果您要复制文件,您可能希望将文件名放在向量中(或按该顺序排列)而不是仅仅显示它们——但大概您知道如何做您想做的事一旦你有文件名可以使用。

无论如何,要调用它,您只需将路径传递到您关心的目录,例如F:/Downloads

show_files("f:/Downloads");

当然,在使用 POSIX 路径的系统下,您将传递不同的输入字符串(例如,可能改为 "/home/some_user/Downloads")。哦,至少在其通常的目录结构中,使用 g++ 时,标头将是 experimental/filesystem 而不仅仅是 filesystem

【讨论】:

    猜你喜欢
    • 2021-12-01
    • 2014-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    • 2018-09-17
    相关资源
    最近更新 更多