Linux 如何删除文件夹中的所有文件,但不删除使用 NIX 标准库的文件夹?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11007494/
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
How to delete all files in a folder, but not delete the folder using NIX standard libraries?
提问by Finding Nemo 2 is happening.
I am trying to create a program that deletes the contents of the /tmp folder, I am using C/C++ on linux.
我正在尝试创建一个删除 /tmp 文件夹内容的程序,我在 linux 上使用 C/C++。
system("exec rm -r /tmp")
deletes everything in the folder but it deletes the folder too which I dont want.
删除文件夹中的所有内容,但它也删除了我不想要的文件夹。
Is there any way to do this by some sort of bash script, called via system()
; or is there a direct way i can do this in C/C++?
有没有办法通过某种名为 via 的 bash 脚本来做到这一点system()
?或者有没有直接的方法可以在 C/C++ 中做到这一点?
My question is similar to this one, but im not on OS X... how to delete all files in a folder, but not the folder itself?
我的问题与此类似,但我不在 OS X 上...如何删除文件夹中的所有文件,而不是文件夹本身?
采纳答案by Jay Sullivan
In C/C++, you could do:
在 C/C++ 中,你可以这样做:
system("exec rm -r /tmp/*")
In Bash, you could do:
在 Bash 中,你可以这样做:
rm -r /tmp/*
This will delete everything inside /tmp, but not /tmp itself.
这将删除 /tmp 中的所有内容,但不会删除 /tmp 本身。
回答by eqzx
by using use the wildcard *
character you can delete all the files with any type of extension.
通过使用通配符,*
您可以删除具有任何类型扩展名的所有文件。
system("exec rm -r /tmp/*")
system("exec rm -r /tmp/*")
回答by ALiX
you can do
你可以做
system("exec find /tmp -mindepth 1 -exec rm {} ';'");
回答by Demitri
#include <stdio.h>
#include <dirent.h>
int main()
{
// These are data types defined in the "dirent" header
DIR *theFolder = opendir("path/of/folder");
struct dirent *next_file;
char filepath[256];
while ( (next_file = readdir(theFolder)) != NULL )
{
// build the path for each file in the folder
sprintf(filepath, "%s/%s", "path/of/folder", next_file->d_name);
remove(filepath);
}
closedir(theFolder);
return 0;
}
You don't want to spawn a new shell via system()
or something like that - that's a lot of overhead to do something very simple and it makes unnecessary assumptions (and dependencies) about what's available on the system.
您不想通过system()
或类似的方式生成新的 shell - 做一些非常简单的事情会产生很多开销,并且它对系统上的可用内容做出了不必要的假设(和依赖性)。
回答by cmllamas
In C/C++ you can use (including hidden directories):
在 C/C++ 中,您可以使用(包括隐藏目录):
system("rm -r /tmp/* /tmp/.*");
system("find /tmp -mindepth 1 -delete");
But what if 'rm' or 'find' utilities are not availabe to sh?, better go 'ftw' and 'remove':
但是,如果 sh 无法使用 'rm' 或 'find' 实用程序怎么办?最好使用 'ftw' 和 'remove':
#define _XOPEN_SOURCE 500
#include <ftw.h>
static int remove_cb(const char *fpath, const struct stat *sb, int typeFlag, struct FTW *ftwbuf)
{
if (ftwbuf->level)
remove(fpath);
return 0;
}
int main(void)
{
nftw("./dir", remove_cb, 10, FTW_DEPTH);
return 0;
}
回答by andrew
I realize this is very old question, but building on Demitri's great answer I created a function that will recursively delete files in subfolders if desired
我意识到这是一个很老的问题,但是基于 Demitri 的出色答案,我创建了一个函数,如果需要,它将递归删除子文件夹中的文件
It also does someerror handling, in that it passes back errno. The function header is written for parsing by doxygen. This function works in the simple example cases I used, and deletes hidden folders and hidden files.
它还进行一些错误处理,因为它会传回 errno。函数头是为doxygen 解析而编写的。此功能适用于我使用的简单示例案例,并删除隐藏文件夹和隐藏文件。
I hope this helps someone else in the future
我希望这可以帮助其他人在未来
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#define SUCCESS_STAT 0
/**
* checks if a specific directory exists
* @param dir_path the path to check
* @return if the path exists
*/
bool dirExists(std::string dir_path)
{
struct stat sb;
if (stat(dir_path.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode))
return true;
else
return false;
}
/**
* deletes all the files in a folder (but not the folder itself). optionally
* this can traverse subfolders and delete all contents when recursive is true
* @param dirpath the directory to delete the contents of (can be full or
* relative path)
* @param recursive true = delete all files/folders in all subfolders
* false = delete only files in toplevel dir
* @return SUCCESS_STAT on success
* errno on failure, values can be from unlink or rmdir
* @note this does NOT delete the named directory, only its contents
*/
int DeleteFilesInDirectory(std::string dirpath, bool recursive)
{
if (dirpath.empty())
return SUCCESS_STAT;
DIR *theFolder = opendir(dirpath.c_str());
struct dirent *next_file;
char filepath[1024];
int ret_val;
if (theFolder == NULL)
return errno;
while ( (next_file = readdir(theFolder)) != NULL )
{
// build the path for each file in the folder
sprintf(filepath, "%s/%s", dirpath.c_str(), next_file->d_name);
//we don't want to process the pointer to "this" or "parent" directory
if ((strcmp(next_file->d_name,"..") == 0) ||
(strcmp(next_file->d_name,"." ) == 0) )
{
continue;
}
//dirExists will check if the "filepath" is a directory
if (dirExists(filepath))
{
if (!recursive)
//if we aren't recursively deleting in subfolders, skip this dir
continue;
ret_val = DeleteFilesInDirectory(filepath, recursive);
if (ret_val != SUCCESS_STAT)
{
closedir(theFolder);
return ret_val;
}
}
ret_val = remove(filepath);
//ENOENT occurs when i folder is empty, or is a dangling link, in
//which case we will say it was a success because the file is gone
if (ret_val != SUCCESS_STAT && ret_val != ENOENT)
{
closedir(theFolder);
return ret_val;
}
}
closedir(theFolder);
return SUCCESS_STAT;
}