2012-03-09 132 views
1

來查找最舊的文件。有沒有一種方法可以在Linux上使用C++

我想構建文件的緩衝區。每30分鐘保存一個新文件。但允許的文件總數是'n'。

因此,當第n + 1個文件被創建時,最舊的文件必須被刪除。

我發現像'dirent.h'和'struct stat'這樣的東西可以幫助訪問目錄,列出所有文件並獲取其屬性。

結構統計不但是創作的給定時間,但只是 - 最後修改,最後訪問,最後狀態的實時變化http://pubs.opengroup.org/onlinepubs/7908799/xsh/sysstat.h.html

請幫助。

上午:增壓現在不可用。

+1

確實聽起來像你只是想要最後修改的屬性。 – 2012-03-09 23:07:34

+0

可能重複[this](http://stackoverflow.com/questions/4842508/how-can-i-determine-a-files-creation-date-in-windows) – rishi 2012-03-09 23:09:08

回答

3

在Linux上,沒有文件創建時間與文件系統元數據中的文件一起保存。有些東西接近它,但不一樣:inode修改時間(這是struct statst_ctime成員)。從stat手冊頁:

場st_ctime通過寫入或通過設置的inode 信息來改變(即,擁有者,組羣,鏈接計數,模式等)。

只要只要你不修改這些屬性,你不寫(大於零字節)文件(S) - 的st_ctime是你的「文件創建時間」。

+0

這是不正確的 - ctime會改變時mtime會發生變化,但它也會在inode信息發生變化時發生變化。 – je4d 2012-03-13 21:37:53

+0

更改mtime時,這是對inode信息的更改,這意味着ctime更改。這不是一個文件創建時間,即使你避免了chowning/chmoding。 – je4d 2012-03-13 23:40:56

+0

你是對的:如果寫入(超過零字節)文件'c_time'改變 - 這是規則的一個例外。 – sirgeorge 2012-03-14 01:11:02

1

我需要一個函數來刪除給定目錄中最早的文件。我使用了系統回調函數,並用C編寫了代碼。您可以從C++中調用它。

#include <stdio.h> 
#include <dirent.h> 
#include <string.h> 
#include <sys/stat.h> 
#include <stdlib.h> 
#include <time.h> 
#include <unistd.h> 

void directoryManager(char *dir, int maxNumberOfFiles){ 
DIR *dp; 
struct dirent *entry, *oldestFile; 
struct stat statbuf; 
int numberOfEntries=0; 
time_t t_oldest; 
double sec; 

time(&t_oldest); 
//printf("now:%s\n", ctime(&t_oldest)); 
if((dp = opendir(dir)) != NULL) { 
    chdir(dir); 
    while((entry = readdir(dp)) != NULL) { 
     lstat(entry->d_name, &statbuf);  
     if(strcmp(".",entry->d_name) == 0 || strcmp("..",entry->d_name) == 0) 
     continue; 
     printf("%s\t%s", entry->d_name, ctime(&statbuf.st_mtime)); 
     numberOfEntries++; 
     if(difftime(statbuf.st_mtime, t_oldest) < 0){ 
      t_oldest = statbuf.st_mtime; 
     oldestFile = entry; 
     } 
    } 
}  

//printf("\n\n\n%s", oldestFile->d_name); 
if(numberOfEntries >= maxNumberOfFiles) 
    remove(oldestFile->d_name); 

//printf("\noldest time:%s", ctime(&t_oldest)); 
closedir(dp); 
} 

int main(){ 
    directoryManager("/home/myFile", 5); 
} 
+0

感謝^ @mehmet – maheshg 2016-01-13 05:40:30

相關問題