[C++]linux下实现rm()函数删除文件或目录

转载请注明原创:http://www.cnblogs.com/StartoverX/p/4600866.htmlhtml

在linux下有两个函数能够用来删除文件:linux

#include <unistd.h>
int unlink(const char *pathname);

unlink函数删除文件系统中的一个名字,若是这个名字是该文件的最后一个link而且该文件没有被任何进程打开,那么删除该文件。不然等到文件被关闭或最后一个link被删除后删除该文件并释放空间。函数

#include <unistd.h>
int rmdir(const char *pathname);

只有当目录为空的时候,rmdir才能删除该目录。spa

 

因为rmdir只能删除空目录文件,因此在删除目录文件以前须要首先删除目录中的全部文件。code

首先实现rm_dir(const string& path)函数删除目录中的全部文件,在rm_dir()中遍历每个文件,若是遇到目录文件,则递归删除该目录文件。htm

//recursively delete all the file in the directory.
int rm_dir(std::string dir_full_path) { DIR* dirp = opendir(dir_full_path.c_str()); if(!dirp) { return -1; } struct dirent *dir; struct stat st; while((dir = readdir(dirp)) != NULL) { if(strcmp(dir->d_name,".") == 0
                || strcmp(dir->d_name,"..") == 0) { continue; } std::string sub_path = dir_full_path + '/' + dir->d_name; if(lstat(sub_path.c_str(),&st) == -1) { Log("rm_dir:lstat ",sub_path," error"); continue; } if(S_ISDIR(st.st_mode)) { if(rm_dir(sub_path) == -1) // 若是是目录文件,递归删除
 { closedir(dirp); return -1; } rmdir(sub_path.c_str()); } else if(S_ISREG(st.st_mode)) { unlink(sub_path.c_str()); // 若是是普通文件,则unlink
 } else { Log("rm_dir:st_mode ",sub_path," error"); continue; } } if(rmdir(dir_full_path.c_str()) == -1)//delete dir itself.
 { closedir(dirp); return -1; } closedir(dirp); return 0; }

实现rm()函数,判断文件类型,若是是目录文件则rm_dir,普通文件则unlink.blog

int rm(std::string file_name) { std::string file_path = file_name; struct stat st; if(lstat(file_path.c_str(),&st) == -1) { return -1; } if(S_ISREG(st.st_mode)) { if(unlink(file_path.c_str()) == -1) { return -1; } } else if(S_ISDIR(st.st_mode)) { if(file_name == "." || file_name == "..") { return -1; } if(rm_dir(file_path) == -1)//delete all the files in dir.
 { return -1; } } return 0; }
相关文章
相关标签/搜索