如何使用C++删除文件夹?
如果没有跨平台的解决方案,那么如何在最流行的操作系统Windows、Linux、Mac、iOS和Android中实现呢?POSIX解决方案是否适用于所有这些操作系统?
如何使用C++删除文件夹?
如果没有跨平台的解决方案,那么如何在最流行的操作系统Windows、Linux、Mac、iOS和Android中实现呢?POSIX解决方案是否适用于所有这些操作系统?
在C++17中,您可以使用std::filesystem
,而在C++14中已经有std::experimental::filesystem
可用。两者都允许使用filesystem::remove()
。
C++17:
#include <filesystem>
std::filesystem::remove("myEmptyDirectoryOrFile"); // Deletes empty directories or single files.
std::filesystem::remove_all("myDirectory"); // Deletes one or more files recursively.
C++14:
#include <experimental/filesystem>
std::experimental::filesystem::remove("myDirectory");
注意1:
这些函数在发生错误时会抛出filesystem_error异常。如果你想避免捕获异常,可以使用带有std::error_code
作为第二个参数的重载版本。例如:
std::error_code errorCode;
if (!std::filesystem::remove("myEmptyDirectoryOrFile", errorCode)) {
std::cout << errorCode.message() << std::endl;
}
注意2:
从不同的编码隐式地转换为std::filesystem::path
,因此您可以将字符串传递给filesystem::remove()
。
在Windows(VisualC ++)中删除文件夹(子文件夹和文件),而不使用Shell API,这是最佳工作样本:
#include <string>
#include <iostream>
#include <windows.h>
#include <conio.h>
int DeleteDirectory(const std::string &refcstrRootDirectory,
bool bDeleteSubdirectories = true)
{
bool bSubdirectory = false; // Flag, indicating whether
// subdirectories have been found
HANDLE hFile; // Handle to directory
std::string strFilePath; // Filepath
std::string strPattern; // Pattern
WIN32_FIND_DATA FileInformation; // File information
strPattern = refcstrRootDirectory + "\\*.*";
hFile = ::FindFirstFile(strPattern.c_str(), &FileInformation);
if(hFile != INVALID_HANDLE_VALUE)
{
do
{
if(FileInformation.cFileName[0] != '.')
{
strFilePath.erase();
strFilePath = refcstrRootDirectory + "\\" + FileInformation.cFileName;
if(FileInformation.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if(bDeleteSubdirectories)
{
// Delete subdirectory
int iRC = DeleteDirectory(strFilePath, bDeleteSubdirectories);
if(iRC)
return iRC;
}
else
bSubdirectory = true;
}
else
{
// Set file attributes
if(::SetFileAttributes(strFilePath.c_str(),
FILE_ATTRIBUTE_NORMAL) == FALSE)
return ::GetLastError();
// Delete file
if(::DeleteFile(strFilePath.c_str()) == FALSE)
return ::GetLastError();
}
}
} while(::FindNextFile(hFile, &FileInformation) == TRUE);
// Close handle
::FindClose(hFile);
DWORD dwError = ::GetLastError();
if(dwError != ERROR_NO_MORE_FILES)
return dwError;
else
{
if(!bSubdirectory)
{
// Set directory attributes
if(::SetFileAttributes(refcstrRootDirectory.c_str(),
FILE_ATTRIBUTE_NORMAL) == FALSE)
return ::GetLastError();
// Delete directory
if(::RemoveDirectory(refcstrRootDirectory.c_str()) == FALSE)
return ::GetLastError();
}
}
}
return 0;
}
int main()
{
int iRC = 0;
std::string strDirectoryToDelete = "c:\\mydir";
// Delete 'c:\mydir' without deleting the subdirectories
iRC = DeleteDirectory(strDirectoryToDelete, false);
if(iRC)
{
std::cout << "Error " << iRC << std::endl;
return -1;
}
// Delete 'c:\mydir' and its subdirectories
iRC = DeleteDirectory(strDirectoryToDelete);
if(iRC)
{
std::cout << "Error " << iRC << std::endl;
return -1;
}
// Wait for keystroke
_getch();
return 0;
}
(注:该链接为文章来源)void remove_dir(char *path)
{
struct dirent *entry = NULL;
DIR *dir = NULL;
dir = opendir(path);
while(entry = readdir(dir))
{
DIR *sub_dir = NULL;
FILE *file = NULL;
char abs_path[100] = {0};
if(*(entry->d_name) != '.')
{
sprintf(abs_path, "%s/%s", path, entry->d_name);
if(sub_dir = opendir(abs_path))
{
closedir(sub_dir);
remove_dir(abs_path);
}
else
{
if(file = fopen(abs_path, "r"))
{
fclose(file);
remove(abs_path);
}
}
}
}
remove(path);
}
path
以/
结尾,则只删除/content/
,并保留空目录本身;另外,if(*(entry->d_name) != '.')
应该检查"."和"..",因为当前的方式不会删除隐藏文件。否则这很好。 - slashmaisBOOL RemoveDirectory( LPCTSTR lpPathName );
rmdir("C:/Documents and Settings/user/Desktop/itsme")
_rmdir
用于Windows,头文件是#include <direct.h>
,我相信与_mkdir
相同。 - Michsystem("rm -r path");
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
int main()
{
cout << "Enter the DirectoryName to Delete : ";
string directoryName;
cin >> directoryName;
string a = "rmdir /s /q " + directoryName;
system(a.c_str());
return 0;
}