Linux中利用c語言刪除某個(gè)目錄下的文件
利用c語言刪除目錄下文件
最近這段時(shí)間工作內(nèi)容是關(guān)于Linux下的簡單文件操作,以前對(duì)于Linux系統(tǒng)下的文件操作函數(shù)都不是太熟悉,經(jīng)過這次實(shí)踐,對(duì)這些函數(shù)使用有了一定的了解
如何創(chuàng)建文件,讀寫文件,這些簡單的我想大家應(yīng)該是比較熟悉的,我所介紹的是如何遍歷某個(gè)目錄,并且刪除該目錄下的文件(可以指定后綴名),并且也可以指定
文件的修改時(shí)間范圍(多少小時(shí)以前的舊文件可以刪除),下面就是簡單的函數(shù)實(shí)現(xiàn),僅供初學(xué)者參考(畢竟我也是初學(xué)者\(yùn)(^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命令的處理動(dòng)作將其刪除
3.find 指定目錄 -type f | xargs rm -f
#用于參數(shù)列表過長;要?jiǎng)h除的文件太多
4.rm-f `find 指定目錄 -type f`
#刪除指定目錄下的全部普通文件
5.for delete in `ls –l 指定目錄路徑`;do rm -f * ;done
#用for循環(huán)語句刪除指定目錄下的所有類型的文件
總結(jié)
到此這篇關(guān)于Linux中利用c語言刪除某個(gè)目錄下文件的文章就介紹到這了,更多相關(guān)Linux用c語言刪除目錄下文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
數(shù)據(jù)結(jié)構(gòu)之Treap詳解
這篇文章主要介紹了數(shù)據(jù)結(jié)構(gòu)之Treap詳解,本文講解了Treap的基本知識(shí)、Treap的基本操作、Treap的高級(jí)操作技巧等,需要的朋友可以參考下2014-08-08
利用C++開發(fā)一個(gè)protobuf動(dòng)態(tài)解析工具
數(shù)據(jù)庫中存儲(chǔ)的protobuf序列化的內(nèi)容,有時(shí)候查問題想直接解析查看內(nèi)容。很多編碼在網(wǎng)上很容易找到編解碼工具,但protobuf沒有找到編解碼工具,可能這樣的需求比較少吧,那就自己用C++實(shí)現(xiàn)一個(gè),感興趣的可以了解一下2023-01-01
Qt QWidget實(shí)現(xiàn)圖片旋轉(zhuǎn)動(dòng)畫
這篇文章主要為大家詳細(xì)介紹了如何使用了Qt和QWidget實(shí)現(xiàn)圖片旋轉(zhuǎn)動(dòng)畫效果,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-12-12

