Linux中利用c語言刪除某個目錄下的文件
利用c語言刪除目錄下文件
最近這段時間工作內(nèi)容是關(guān)于Linux下的簡單文件操作,以前對于Linux系統(tǒng)下的文件操作函數(shù)都不是太熟悉,經(jīng)過這次實踐,對這些函數(shù)使用有了一定的了解
如何創(chuàng)建文件,讀寫文件,這些簡單的我想大家應(yīng)該是比較熟悉的,我所介紹的是如何遍歷某個目錄,并且刪除該目錄下的文件(可以指定后綴名),并且也可以指定
文件的修改時間范圍(多少小時以前的舊文件可以刪除),下面就是簡單的函數(shù)實現(xiàn),僅供初學(xué)者參考(畢竟我也是初學(xué)者\(^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 指定目錄*
#最經(jīng)典的方法,刪除指定目錄下的所有類型的文件
2.find 指定目錄 -type f -delete或find 指定目錄 -type f -exec rm -f {} \;
#用find命令查找指定目錄下的所有普通文件并刪除or用find命令的處理動作將其刪除
3.find 指定目錄 -type f | xargs rm -f
#用于參數(shù)列表過長;要刪除的文件太多
4.rm-f `find 指定目錄 -type f`
#刪除指定目錄下的全部普通文件
5.for delete in `ls –l 指定目錄路徑`;do rm -f * ;done
#用for循環(huán)語句刪除指定目錄下的所有類型的文件
總結(jié)
到此這篇關(guān)于Linux中利用c語言刪除某個目錄下文件的文章就介紹到這了,更多相關(guān)Linux用c語言刪除目錄下文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++用read()和write()讀寫二進制文件的超詳細教程
二進制的文件肉眼我們是讀不懂的,如果通過二進制的讀寫操作就可以讀懂,下面這篇文章主要給大家介紹了關(guān)于C++用read()和write()讀寫二進制文件的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-06-06

