2012-03-09 24 views
1

Linuxの場合。には、C++を使用して最も古いファイルを見つける方法があります。

私はファイルのバッファを構築したいと思います。 30分ごとに新しいファイルが保存されます。しかし、許可されたファイルの総数は 'n'です。

「n + 1」番目のファイルが作成されるとき、最も古いファイルを削除する必要があります。

ディレクトリにアクセスしてすべてのファイルを一覧表示し、そのプロパティを取得するのに役立つ「dirent.h」や「struct stat」のようなものが見つかりました。

のstruct statにないしかし、創造の所与の時間はありませんが、ちょうど - 最後の最後にアクセスし、変更され、最後のステータスの時間は

助けてくださいhttp://pubs.opengroup.org/onlinepubs/7908799/xsh/sysstat.h.htmlを変更しました。

P.S:現在、ブーストは利用できません。

+1

最後に変更された統計情報が必要なように聞こえます。 –

+0

可能性のある繰り返し[this](http://stackoverflow.com/questions/4842508/how-can-i-determine-a-files-creation-date-in-windows) – rishi

答えて

3

Linuxでは、ファイルシステムのメタデータにファイルとともに保存されたファイル作成時間はありません。それに近いものがありますが、同じものではありません。inode変更時刻(これはのst_ctimeメンバーです)。 stat manページから:

フィールドファイルのst_ctimeを書き込むことによって、またはiノードに 情報を設定することにより、変更された(すなわち、所有者、グループグループ、リンク数、モードなど)。

これらのプロパティを変更しないと、ファイル(複数可)に(以上、ゼロバイト)を書き込みませんとして限り - st_ctimeは、あなたの「ファイル作成時間」です。

+0

これは間違っています - ctimeはmtimeは変更されますが、inode情報が変更されたときにも変更されます。 – je4d

+0

mtimeが変更された場合、これはiノード情報が変更されたことになります。つまり、ctimeが変更されます。 chowning/chmodingを避ける場合でも、ファイル作成時間ではありません。 – je4d

+0

あなたは正しいです:ファイルに(0バイト以上)を書き込む場合、 'c_time'が変更されます - これはルールからの例外です。 – sirgeorge

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

関連する問題