【问题标题】:is there a way to find the oldest file using just the c++有没有办法只使用 c++ 找到最旧的文件
【发布时间】:2012-03-09 23:03:03
【问题描述】:

在 Linux 上。

我想建立一个文件缓冲区。每 30 分钟保存一个新文件。但允许的文件总数为 'n'。

因此,当创建第 'n+1' 个文件时,必须删除最旧的文件。

我发现了诸如“dirent.h”和“struct stat”之类的东西,它们可以帮助访问目录、列出所有文件并获取其属性。

struct stat 但是没有给出创建时间,而只是 - 最后修改,最后访问,最后状态更改的时间http://pubs.opengroup.org/onlinepubs/7908799/xsh/sysstat.h.html

请帮忙。

P.S: boost 目前不可用。

【问题讨论】:

  • 当然听起来你只想要最后修改的统计数据。
  • this的可能重复

标签: c++ linux file-io


【解决方案1】:

在 Linux 上,没有文件创建时间与文件系统元数据中的文件一起保存。有一些接近它,但不一样:inode 修改时间(这是struct statst_ctime 成员)。来自stat 手册页:

字段 st_ctime 通过写入或设置 inode 进行更改 信息(即所有者、组组、链接计数、模式等)。

只要您不修改这些属性并且您不写入(超过零字节)到文件 - st_ctime 是您的“文件创建时间”。

【讨论】:

  • 这是不正确的——ctime会随着mtime的变化而变化,但它会随着inode信息的变化而变化。
  • 当mtime发生变化时,就是inode信息发生了变化,也就是ctime发生了变化。这不是文件创建时间,即使您避免 chowning/chmoding。
  • 你是对的:如果写入(超过零字节)到文件,'c_time' 会发生变化 - 这是规则的一个例外。
【解决方案2】:

我需要一个删除给定目录中最旧文件的函数。我使用了系统回调函数,并用 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);
}

【讨论】:

    猜你喜欢
    • 2012-12-14
    • 2020-11-24
    • 2022-01-21
    • 1970-01-01
    • 2011-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多