我正在尝试创建一个删除/tmp 文件夹内容的程序,我在 linux 上使用 C/C++。
system("exec rm -r /tmp")
删除文件夹中的所有内容,但它也删除了我不想要的文件夹。
有没有办法通过某种 bash 脚本来做到这一点,通过 system()
调用;还是有直接的方法我可以在 C/C++ 中做到这一点?
我的问题与此类似,但我不在 OS X 上... how to delete all files in a folder, but not the folder itself?
最佳答案
#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;
}
你不想通过 system()
或类似的东西生成一个新的 shell - 做一些非常简单的事情会产生很多开销,并且它对什么是不必要的假设(和依赖关系)在系统上可用。
关于c++ - 如何删除文件夹中的所有文件,但不使用 NIX 标准库删除文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11007494/