AMM*_*AMM 10 c++ linux directory
我正在Linux上编写一个c ++程序(Ubuntu).我想删除目录的内容.它可以是松散的文件或子目录.
从本质上讲,我想做一些相当于的事情
rm -rf <path-to-directory>/*
Run Code Online (Sandbox Code Playgroud)
你能否在c ++中建议最好的方法以及所需的标题.是否可以使用sys/stat.h或sys/types.h或sys/dir.h执行此操作?
caf*_*caf 31
使用nftw()带有FTW_DEPTH标志的(File Tree Walk)功能.提供一个只调用remove()传递文件的回调:
#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <ftw.h>
#include <unistd.h>
int unlink_cb(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf)
{
int rv = remove(fpath);
if (rv)
perror(fpath);
return rv;
}
int rmrf(char *path)
{
return nftw(path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
}
Run Code Online (Sandbox Code Playgroud)
如果您不想删除基本目录本身,请更改该unlink_cb()功能以检查级别:
int unlink_cb(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf)
{
int rv;
if (ftwbuf->level == 0)
return 0;
rv = remove(fpath);
if (rv)
perror(fpath);
return rv;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4456 次 |
| 最近记录: |