作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我正在 Linux (Ubuntu) 上编写一个 C++ 程序。我想删除一个目录的内容。它可以是松散的文件或子目录。
本质上,我想做一些等同于
的事情rm -rf <path-to-directory>/*
您能否建议在 C++ 中执行此操作的最佳方法以及所需的 header 。是否可以使用 sys/stat.h 或 sys/types.h 或 sys/dir.h 执行此操作?!
最佳答案
使用 nftw()
(文件树遍历)函数,带有 FTW_DEPTH
标志。提供一个仅在传递的文件上调用 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);
}
如果不想删除基目录本身,更改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;
}
关于c++ - 如何在 Linux 上用 C++ 清除目录内容(基本上,我想做 'rm -rf <directorypath>/*',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3184445/
使用登录后,我想吐出用户名。 但是,当我尝试单击登录按钮时, 它给了我力量。 我看着logcat,但是什么也没显示。 这种编码是在说。 它将根据我在登录屏幕中输入的名称来烘烤用户名。 不会有任何密码。
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 这个问题似乎是题外话,因为它缺乏足够的信息来诊断问题。 更详细地描述您的问题或include a min
我是一名优秀的程序员,十分优秀!