ver por mtime modificacion listar fecha ejemplos creacion comandos comando cambiar basicos archivos archivo anterior c linux

por - ¿Cómo obtener la fecha de creación del archivo en Linux?



mtime linux (4)

Estoy trabajando con lotes de archivos que contienen información sobre el mismo objeto en los diferentes momentos de su vida, y la única forma de ordenarlos es por fecha de creación. Estaba usando esto:

//char* buffer has the name of file struct stat buf; FILE *tf; tf = fopen(buffer,"r"); //check handle fstat(tf, &buf); fclose(tf); pMyObj->lastchanged=buf.st_mtime;

Pero eso no parece funcionar. ¿Qué estoy haciendo mal? ¿Hay otras maneras más confiables / simples de obtener la fecha de creación del archivo en Linux?


La hora de creación del archivo no se almacena en ningún lugar; solo puede recuperar una de las siguientes opciones:

time_t st_atime; /* time of last access */ time_t st_mtime; /* time of last modification */ time_t st_ctime; /* time of last status change */

Sin embargo, su código debería darle la última modificación. Nota: puede usar stat() lugar de fstat() sin abrir el archivo ( stat() toma el nombre del archivo como param).


Para obtener la fecha de creación del archivo en Linux, uso el siguiente método

root@sathishkumar# cat << _eof > test.txt > Hello > This is my test file > _eof root@sathishkumar# cat test.txt Hello This is my test file root@sathishkumar# ls -i test.txt 2097517 test.txt root@sathishkumar# debugfs -R ''stat <2097517>'' /dev/sda5 Inode: 2097517 Type: regular Mode: 0664 Flags: 0x80000 Generation: 4245143992 Version: 0x00000000:00000001 User: 1000 Group: 1000 Size: 27 File ACL: 0 Directory ACL: 0 Links: 1 Blockcount: 8 Fragment: Address: 0 Number: 0 Size: 0 ctime: 0x50ea6d84:4826cc94 -- Mon Jan 7 12:09:00 2013 atime: 0x50ea6d8e:75ed8a04 -- Mon Jan 7 12:09:10 2013 mtime: 0x50ea6d84:4826cc94 -- Mon Jan 7 12:09:00 2013 crtime: 0x5056d493:bbabf49c -- Mon Sep 17 13:13:15 2012 Size of extra inode fields: 28 EXTENTS: (0):8421789

atime: Último archivo de tiempo fue abierto o ejecutado

ctime: Hora en que se actualizó la información del inodo. ctime también se actualiza cuando se modifica el archivo

mtime: hora de la última modificación

crtime: hora de creación del archivo


La aproximación más cercana a ''fecha de creación'' es el miembro st_ctime en la struct stat , pero que en realidad registra la última vez que el inodo cambió. Si crea el archivo y nunca modifica su tamaño o permisos, eso funciona como una hora de creación. De lo contrario, no hay registro de cuándo se creó el archivo, al menos en los sistemas Unix estándar.

Para sus propósitos, ordene por st_mtime ... u obtenga los archivos nombrados con una marca de tiempo en el nombre.

Tenga en cuenta que si está en Darwin (Mac OS X), el tiempo de creación está disponible. De la página man para stat(2) :

Sin embargo, cuando se define la macro _DARWIN_FEATURE_64_BIT_INODE , la estructura de estadísticas se definirá ahora como:

struct stat { /* when _DARWIN_FEATURE_64_BIT_INODE is defined */ dev_t st_dev; /* ID of device containing file */ mode_t st_mode; /* Mode of file (see below) */ nlink_t st_nlink; /* Number of hard links */ ino_t st_ino; /* File serial number */ uid_t st_uid; /* User ID of the file */ gid_t st_gid; /* Group ID of the file */ dev_t st_rdev; /* Device ID */ struct timespec st_atimespec; /* time of last access */ struct timespec st_mtimespec; /* time of last data modification */ struct timespec st_ctimespec; /* time of last status change */ struct timespec st_birthtimespec; /* time of file creation(birth) */ off_t st_size; /* file size, in bytes */ blkcnt_t st_blocks; /* blocks allocated for file */ blksize_t st_blksize; /* optimal blocksize for I/O */ uint32_t st_flags; /* user defined flags for file */ uint32_t st_gen; /* file generation number */ int32_t st_lspare; /* RESERVED: DO NOT USE! */ int64_t st_qspare[2]; /* RESERVED: DO NOT USE! */ };

Tenga en cuenta el campo st_birthtimespec . Tenga en cuenta, también, que todos los tiempos están en valores struct timespec , por lo que hay una temporización por segundo ( tv_nsec da una resolución de nanosegundos). POSIX 2008 <sys/stat.h> requiere el tiempo de struct timespec manteniendo los tiempos estándar; Darwin sigue eso.


fstat funciona en descriptores de archivos, no en estructuras de ARCHIVO. La versión más simple:

#include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #ifdef HAVE_ST_BIRTHTIME #define birthtime(x) x.st_birthtime #else #define birthtime(x) x.st_ctime #endif int main(int argc, char *argv[]) { struct stat st; size_t i; for( i=1; i<argc; i++ ) { if( stat(argv[i], &st) != 0 ) perror(argv[i]); printf("%i/n", birthtime(st)); } return 0; }

Tendrá que averiguar si su sistema tiene st_birthtime en su estructura estadística inspeccionando sys / stat.h o utilizando algún tipo de construcción autoconf.