Linux中利用c語言刪除某個目錄下的檔案
阿新 • • 發佈:2021-01-13
利用c語言刪除目錄下檔案
最近這段時間工作內容是關於Linux下的簡單檔案操作,以前對於Linux系統下的檔案操作函式都不是太熟悉,經過這次實踐,對這些函式使用有了一定的瞭解
如何建立檔案,讀寫檔案,這些簡單的我想大家應該是比較熟悉的,我所介紹的是如何遍歷某個目錄,並且刪除該目錄下的檔案(可以指定字尾名),並且也可以指定
檔案的修改時間範圍(多少小時以前的舊檔案可以刪除),下面就是簡單的函式實現,僅供初學者參考(畢竟我也是初學者\(^o^)/~)
#include <stdio.h> #include <fcntl.h> #include <time.h> #include <string.h> #include <dirent.h> #include <sys/stat.h> #include <unistd.h> #define FILE_MAX_LEN 256 void rmv_old_files(const char *path,const char *suf,int hours) { char filename[FILE_MAX_LEN] = {0}; struct tm *TM; struct dirent *dirp; struct stat statbuf; DIR *dp = NULL; time_t curr_time; int nameLen,offset; char *chTemp = NULL; curr_time = time((time_t*)NULL); dp = opendir(path); if (NULL == dp) { return; } while((dirp=readdir(dp)) != NULL) { if (strcmp(dirp->d_name,".")==0 || strcmp(dirp->d_name,"..")==0) { continue; } nameLen = strlen(dirp->d_name); chTemp = dirp->d_name; if (*suf != '\0') { offset = nameLen-strlen(suf); if (offset<0 || strncmp(suf,chTemp+offset,strlen(suf))!=0) { continue; } } sprintf(filename,"%s%s",path,dirp->d_name); if (!stat(filename,&statbuf)) { /*check the st_mtime of the file,if more than retention_hours ago then delete it*/ if (curr_time-statbuf.st_mtime >= hours*3600 && S_ISREG(statbuf.st_mode)) { unlink(filename); } } } closedir(dp); }
附:linux刪除指定目錄下的檔案命令
rm -f 指定目錄*
#最經典的方法,刪除指定目錄下的所有型別的檔案
2.find 指定目錄 -type f -delete或find 指定目錄 -type f -exec rm -f {} \;
#用find命令查詢指定目錄下的所有普通檔案並刪除or用find命令的處理動作將其刪除
3.find 指定目錄 -type f | xargs rm -f
#用於引數列表過長;要刪除的檔案太多
4.rm-f `find 指定目錄 -type f`
#刪除指定目錄下的全部普通檔案
5.for delete in `ls –l 指定目錄路徑`;do rm -f * ;done
#用for迴圈語句刪除指定目錄下的所有型別的檔案
總結
到此這篇關於Linux中利用c語言刪除某個目錄下檔案的文章就介紹到這了,更多相關Linux用c語言刪除目錄下檔案內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!