C、C++创建和删除文件夹操作

创建文件夹

1、调用Window API函数

BOOL CreateDirectory(LPCTSTR lpPathName,
                     LPSECURITY_ATTRIBUTES lpSecurityAttributes);

头、库文件
Winbase.h, Coredll.lib

参数:
- lpPathName:字符串指针,要创建的文件夹的路径。
- lpSecurityAttributes:忽略,设置为NULL。

返回值:
成功-非零,失败-零。查看错误使用GeLastError();

备注:
1. 该函数不能创建多层文件夹。
2. 该函数是同步操作,对应的异步操作函数为CeCreateDirectory


int SHCreateDirectory(HWND hwnd, 
                      LPCWSTR pszPath);

头、库文件
shlobj.h,shell32.lib

参数:
- hwnd:父窗口的句柄。一般设置为空。
- pszPath:字符串指针,要创建的文件夹的路径。

返回值:
ERROR_SUCCESS-成功

返回值 内容
ERROR_BAD_PATHNAME The pszPath parameter was set to a relative path.
ERROR_FILENAME_EXCED_RANGE The path pointed to by pszPath is too long.
ERROR_FILE_EXISTS the directory exists.
ERROR_ALREADY_EXITSTS the directory exists.
ERROR_CANCELLED The user canceled the operation.

备注:
1. 相比CreateDirectory,该函数可以创建多层文件夹。

注意:
1. 以上两个函数都限制创建的文件夹的路径不能超过MAX_PATH个字符,这限制跟该函数如何解析路径有关。
2、以上两个函数都是对应的Ex版本,CreateDirectoryEx, SHCreateDirectoryEx.

2、调用C运行库函数

int _mkdir(const char* dirname);

int _wmkdir(const wchar_t* dirname);

头、库文件:
direct.h或者wchar.h,c运行库

宏定义:

tchar.h _MBCS defined _UNICODE defined
_tmkdir _mkdir _wmkdir

参数:
- dirname:字符串指针,要创建的文件夹的路径。

返回值:
0-成功,-1-失败。

errno content
EEXIST Directory was not created because dirname is the name of an existing file, directory, or device.
ENOENT Path was not found.

For more information about these and other return codes, see _doserrno, errno, _sys_errlist, and _sys_nerr.

删除文件夹

1、调用Windows API函数

BOOL RemoveDirectory(LPCTSTR lpPathName);

头、库文件
Winbase.h, Coredll.lib

参数:
- lpPathName:字符串指针,要删除的文件夹的路径。

返回值:
成功-非零,失败-零。查看错误使用GeLastError();

备注:
1、RemoveDirectory only operates on empty directories. If the directory is not empty, an application must first use FindFirstFile, FindNextFile, RemoveDirectory and DeleteFile to recursively enumerate and delete the files and subdirectories inside the directory.

2、调用C运行库函数

int _rmdir(const char* dirname);

int _wrmdir(const wchar_t* dirname);

头、库文件:
direct.h或者wchar.h,c运行库

宏定义:

tchar.h _MBCS defined _UNICODE defined
_trmdir _rmdir _wrmdir

参数:
- dirname:字符串指针,要删除的文件夹的路径。

返回值:
0-成功,-1-失败。

errno content
ENOTEMPTY Given path is not a directory, the directory is not empty, or the directory is either the current working directory or the root directory.
ENOENT Path was not found.
EACCES A program has an open handle to the directory.

For more information about these and other return codes, see _doserrno, errno, _sys_errlist, and _sys_nerr.

备注:
1、The directory must be empty, and it must not be the current working directory or the root directory.

你可能感兴趣的:(C/C++,日常积累)