Linux文件操作:利用C語言刪除某個目錄下的文件


利用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刪除指定目錄下的文件命令

1.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循環語句刪除指定目錄下的所有類型的文件

總結

到此利用c語言刪除某個目錄下文件的文章就介紹到這了。最后,特別推薦一個分享C/C++和算法的優質內容,學習交流,技術探討,面試指導,簡歷修改...還有超多源碼素材等學習資料,零基礎的視頻等着你!

還沒關注的小伙伴,可以長按關注一下:


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM