且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我需要使用c ++在另一个目录中创建一个目录(文件夹)

更新时间:2023-11-30 14:07:58

您的代码有两个(或者三个)问题:



1.必须转义反斜杠(带前缀)另一个反斜杠)。所以你的路径必须是:
There are two (or maybe three) problems with your code:

1. Back slashes must be escaped (prefixed with another backslash). So your path must be:
"C:\\MyStuff\\Myzone\\Documents\\confidential\\work"


2. CreateDirectory 一次只能创建一个目录。所以你必须调用它两次(先用C:\\MyStuff \\Myzone \\Documents\\confidential然后再用C:\\MyStuff \\ Myzone \\\Documents\\confidential\\work)。



3.您必须拥有在上层路径中创建目录的权限。 />


您应该始终检查 CreateDirectory 的返回值并调用 GetLastError 无法更多地了解失败的原因。



[更新]

SHCreateDirectoryEx [ ^ ]函数也可以创建中间目录。所以你可以改用它。但请阅读说明。


2. CreateDirectory can only create one directory at a time. So you must call it twice (first with "C:\\MyStuff\\Myzone\\Documents\\confidential" and then with "C:\\MyStuff\\Myzone\\Documents\\confidential\\work").

3. You must have the privileges to create directories in the upper path.

You should always check the return value of CreateDirectory and call GetLastError upon failures to know more about the reason of the failure.

[UPDATE]
The SHCreateDirectoryEx[^] function is able to create intermediate directories as well. So you might use this instead. But read the notes.


嗯,我终于想出了一个解决方案..没什么了不起但它可以工作,你可以一次创建子目录!



所以这是我的解决方案:



Umm I finally came up with a solution..nothing great but it works and you can create sub directories at one shot !

So here's my solution :

#include "stdafx.h"
#include "process.h"
#include "iostream"
#include "windows.h"
#include "string"
#include "tchar.h"

 static class program
{
public :

 static BOOL CreateFullDirectory(LPCTSTR dirName, LPSECURITY_ATTRIBUTES lpSA)
{

    TCHAR tmpName[255];
    _tcscpy(tmpName, dirName);

    // Create parent directories
    for (LPTSTR p = _tcschr(tmpName, _T('/')); p; p = _tcschr(p + 1, _T('/')))
    {
        *p = 0;
        ::CreateDirectory(tmpName, lpSA);  // may or may not already exist
        *p = _T('/');
    }	

    return CreateDirectory(dirName, lpSA);
}
};

int main()
{
	
	program::CreateFullDirectory("C:/MyStuff/Myzone/Documents/confidential/work", NULL);
}





如果你们知道更好的事情,请发表你的答案:)



If you guys know anything better then kindly post your answers :)