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

Fin*_*ng. 23 c c++ unix linux

我正在尝试创建一个删除/ tmp文件夹内容的程序,我在linux上使用C/C++.

system("exec rm -r /tmp")
Run Code Online (Sandbox Code Playgroud)

删除文件夹中的所有内容,但它也删除了我不想要的文件夹.

有没有办法通过某种bash脚本来做到这一点,称为via system(); 还是有直接的方式我可以在C/C++中做到这一点?

我的问题类似于这个,但我不在OS X上... 如何删除文件夹中的所有文件,而不是文件夹本身?

Dem*_*tri 48

#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;
}
Run Code Online (Sandbox Code Playgroud)

你不希望通过system()类似的方式产生一个新的shell - 这是一个非常简单的事情,并且它对系统上可用的内容做出了不必要的假设(和依赖关系).

  • 你可能想设置`if(0 == strcmp(next_file-> d_name,".")|| 0 == strcmp(next_file-> d_name,"..")){continue; 如果你不想删除文件,那么在while语句的开头"." 和"......" (7认同)
  • 最好的答案:) (6认同)

Jay*_*van 15

在C/C++中,你可以这样做:

system("exec rm -r /tmp/*")
Run Code Online (Sandbox Code Playgroud)

在Bash中,您可以这样做:

rm -r /tmp/*
Run Code Online (Sandbox Code Playgroud)

这将删除/ tmp中的所有内容,但不删除/ tmp本身.

  • 嗯......这将删除文件夹中的所有可见文件(即那些*扩展为),但不会删除任何以.开头的文件. (7认同)
  • 任何从 C 调用“system”都是不安全的。https://www.securecoding.cert.org/confluence/pages/viewpage.action?pageId=2130132 (2认同)