在C 中打开目录
Opening a directory in c++
我正在尝试编写一个将文件从一个目录移至另一个目录的程序,到目前为止,我已经写了此。
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没有dirent.h库,而opendir和封闭式所需的库,所以我想知道是否有类似或更好的做事方式。
您的代码现在没有多大意义。
一方面,file_move
采用ifstream和ofstream,这意味着您已经找到并打开了您关心的文件。然后它继续尝试搜索文件...
目前,我假设您需要搜索您关心的文件。在这种情况下,您可能要使用filesystem
库。有了真正的最新编译器,可以直接在std::
中。对于稍旧的编译器,它可能在std::experimental
中。对于较老的人(早于文件系统ts),您可能需要使用Boost文件系统。
无论如何,使用此操作的代码将运行类似的内容:
#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
。
相关文章:
- 没有找到相关文章