21xrx.com
2025-03-27 09:49:21 Thursday
文章检索 我的文章 写文章
C++如何创建文件夹?
2023-06-26 00:56:14 深夜i     31     0
C++ 创建 文件夹 代码实现 目录操作

在C++中,我们可以使用Windows API中的函数来创建文件夹。在这篇文章中,我们将介绍如何使用C++的Windows API来创建文件夹。

1. 使用CreateDirectory函数

CreateDirectory函数可以在指定路径下创建一个新的文件夹,其函数原型如下:

BOOL CreateDirectory(
  LPCTSTR lpPathName,
  LPSECURITY_ATTRIBUTES lpSecurityAttributes
);

其中,lpPathName是新文件夹的完整路径,lpSecurityAttributes可以为NULL。

下面是CreateDirectory函数的一个示例代码:

#include <Windows.h>
#include <iostream>
using namespace std;
int main()
{
  LPCSTR pathName = "C:\\test\\newFolder";
  BOOL result = CreateDirectory(pathName, NULL);
  if (result == FALSE)
  
    cout << "文件夹创建失败!" << endl;
  
  else
  
    cout << "文件夹创建成功!" << endl;
  
  system("pause");
  return 0;
}

上述代码中,我们使用了CreateDirectory函数来创建一个文件夹,路径为C:\test\newFolder,其中test为一个已经存在的文件夹。

2. 使用SHCreateDirectoryEx函数

SHCreateDirectoryEx函数是Shell API中的一个函数,其可以在指定路径下创建一个新的文件夹,并且可以递归地创建整个文件夹路径。

其函数原型如下:

HRESULT SHCreateDirectoryEx(
  HWND       hwnd,
  LPCTSTR      pszPath,
  const SECURITY_ATTRIBUTES *psa
);

其中,hwnd为可选的窗口句柄,pszPath为新文件夹的完整路径,psa可以为NULL。

下面是SHCreateDirectoryEx函数的一个示例代码:

#include <Windows.h>
#include <Shlwapi.h>
#include <iostream>
#pragma comment(lib,"Shlwapi.lib")
using namespace std;
int main()
{
  LPCWSTR pathName = L"C:\\test\\newFolder\\anotherFolder";
  HRESULT result = SHCreateDirectoryEx(NULL, pathName, NULL);
  if (result != ERROR_SUCCESS)
  
    cout << "文件夹创建失败!" << endl;
  
  else
  
    cout << "文件夹创建成功!" << endl;
  
  system("pause");
  return 0;
}

上述代码中,我们使用了SHCreateDirectoryEx函数来创建一个文件夹,路径为C:\test\newFolder\anotherFolder,其中test和newFolder都是已经存在的文件夹。需要注意的是,SHCreateDirectoryEx函数在调用前需要引入Shlwapi.lib库。

总结:

以上就是C++如何创建文件夹的两种方法。无论是CreateDirectory函数还是SHCreateDirectoryEx函数,它们都非常简单易用,可以帮助开发人员快速地实现文件夹的创建操作。

  
  
下一篇: C++ 访问控制

评论区