c++ - 如何删除文件夹中的所有文件,但不使用 NIX 标准库删除文件夹?

标签 c++ c linux unix

我正在尝试创建一个删除/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/

相关文章:

c++ - C 和 C++ 中的原始内存是什么?

c - Makefile:通配符和 patsubst 不会更改文件源名称

c - C中的Escape键无限循环

Java Linux shell 应用程序

linux - 使用命令替换保存变量...找不到命令

c - 获取不同的 X 显示空闲时间 - C 代码

c++ - 如何将 std::map 传递给 VS2013 中的可变参数模板?

C++14类函数错误: "Object has no attribute ' value'"

c++ - "int* const* num"是什么意思?

c - 从 C 到 gnuplot 的曲面绘图管道