轉載請註明原創: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; }