我正在尝试创建一个删除/ 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 - 这是一个非常简单的事情,并且它对系统上可用的内容做出了不必要的假设(和依赖关系).
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本身.
归档时间: |
|
查看次数: |
47583 次 |
最近记录: |