Linux檔案操作 利用C語言刪除某個目錄下的檔案

2022-06-22 09:33:18 字數 2007 閱讀 1317

利用c語言刪除目錄下檔案

最近這段時間工作內容是關於linux下的簡單檔案操作,以前對於linux系統下的檔案操作函式都不是太熟悉,經過這次實踐,對這些函式使用有了一定的了解。

如何建立檔案,讀寫檔案,這些簡單的我想大家應該是比較熟悉的,我所介紹的是如何遍歷某個目錄,並且刪除該目錄下的檔案(可以指定字尾名),並且也可以指定檔案的修改時間範圍(多少小時以前的舊檔案可以刪除),下面就是簡單的函式實現,僅供初學者參考(畢竟我也是初學者\(^o^)/~)

#include

#include

#include

#include

#include

#include

#include

#define file_max_len 256

void rmv_old_files(const char *path, const char *suf, int hours)

char filename[file_max_len] = ;

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迴圈語句刪除指定目錄下的所有型別的檔案

總結還沒關注的小夥伴,可以長按關注一下:

Linux下C語言的檔案操作

檔案的讀寫 include include include include include include include define buffsize 512 define msg hhhh9999 intmain int main,char ar printf open file return...

Linux下C語言的檔案操作

檔案的讀寫 include include include include include include include define buffsize 512 define msg hhhh9999 intmain int main,char ar printf open file return...

c語言檔案操作

rt null ch fgetc fp while ch eof fclose fp 本 例程式的功能是從檔案中逐個讀取字元,在螢幕上顯示。程式定義了檔案指標fp,以讀文字檔案方式開啟檔案 d jrzh example ex1 1.c 並使fp指向該檔案。如開啟檔案出錯,給出提示並退出程式。程式第1...