溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

利用c語言怎么在刪除Linux系統(tǒng)中某個目錄下的文件

發(fā)布時間:2021-01-12 14:42:46 來源:億速云 閱讀:326 作者:Leah 欄目:開發(fā)技術

這篇文章將為大家詳細講解有關利用c語言怎么在刪除Linux系統(tǒng)中某個目錄下的文件,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。

利用c語言刪除目錄下文件

#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

#用于參數(shù)列表過長;要刪除的文件太多

4.rm-f `find 指定目錄 -type f`

#刪除指定目錄下的全部普通文件

5.for delete in `ls –l 指定目錄路徑`;do rm -f * ;done

#用for循環(huán)語句刪除指定目錄下的所有類型的文件

關于利用c語言怎么在刪除Linux系統(tǒng)中某個目錄下的文件就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI