C++ 如何在C++中创建目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8931196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:21:12  来源:igfitidea点击:

How to create a directory in C++

c++windowsapic++17mkdir

提问by user1143336

i just found a little piece of code that let me create a directory with windows API without using system(). The only problem is that i can't create directory in subdirectory. For example

我刚刚找到了一小段代码,可以让我在不使用 system() 的情况下使用 Windows API 创建一个目录。唯一的问题是我无法在子目录中创建目录。例如

#include<windows.h>

int main(){
   CreateDirectory ("C:\random", NULL);
   return 0;
}

Create a folder named random in C.

在 C 中创建一个名为 random 的文件夹。

But if i do

但如果我这样做

#include<windows.h>

int main(){
   CreateDirectory ("C:\Users\morons", NULL);
   return 0;
}

It creates in C che folder named Usersmorons and not the folder morons under Users. Any suggest?

它在名为 Usersmorons 的 C che 文件夹中创建,而不是在用户下的文件夹 morons。有什么建议吗?

回答by josephthomas

You will need admin access to create or delete a folder in C:\Users. Make sure that you are running the .exe as admin, to ensure you have these privileges. If you do not, then CreateDirectory will fail.

您将需要管理员访问权限才能在 C:\Users 中创建或删除文件夹。确保您以管理员身份运行 .exe,以确保您拥有这些权限。如果不这样做,则 CreateDirectory 将失败。

To get the error that is returned, use GetLastError. For a reference on the errors that may return, please take a look at the "Return value" section at

要获取返回的错误,请使用 GetLastError。有关可能返回的错误的参考,请查看“返回值”部分

http://msdn.microsoft.com/en-us/library/windows/desktop/aa363855%28v=vs.85%29.aspx

http://msdn.microsoft.com/en-us/library/windows/desktop/aa363855%28v=vs.85%29.aspx

Also, the code you are looking for is

此外,您正在寻找的代码是

CreateDirectory ("C:\Users\morons", NULL);

As there needs to be a "\\" before "morons"

因为在“白痴”之前需要一个“\\”

回答by Anodyne

You need another backslash in there:

你需要另一个反斜杠:

CreateDirectory ("C:\Users\morons", NULL);

回答by Tony Tannous

Making a windows application cross-platform, was using CreateDirectory()c++17 standard now has std::filesystem::create_directories

制作跨平台的 windows 应用程序,使用CreateDirectory()c++17 标准现在有std::filesystem::create_directories

#include<iostream>
#include <filesystem>

int main()
{
    std::filesystem::create_directories("C:\newfolder\morons");
}

Needs changes in makefile to -std=c++17and updating to a GCC compiler that supports c++17.

需要更改生成文件-std=c++17并更新到支持 c++17 的 GCC 编译器。

In visual studio follow steps hereto enable c++17

在 Visual Studio 中,按照此处的步骤启用 c++17