Get create time file linux

Дата создания файла в Linux

В свойствах файла в файловом менеджере Linux зачастую отображается только информация о дате последнего обращения к нему и дате изменения. Но вот дата создания там, к сожалению, отсутствует. А иногда нужно посмотреть именно ее, например, чтобы узнать, с какого момента ведется запись лога.

В данной статье мы расскажем о том, какие данные хранятся в файловых системах Linux и объясним, как узнать дату создания файла Linux . Будут упомянуты сразу же два удобных способа, каждый из которых со своими особенностями.

Дата создания файла Linux

В стандарте POSIX прописаны только 3 вида временных меток, которые должна хранить файловая система:

  • atime – время последнего обращения к файлу.
  • mtime – время последнего изменения содержимого.
  • ctime – время последней модификации прав доступа или владельца.

По этой причине в старых файловых системах посмотреть информацию о дате создания файла зачастую невозможно. А вот в современных файловых системах (ext4, zfs, XFS и т. д.) она уже сохраняется.

Данные о дате создания записываются в специальном поле:

Есть два удобных способа просмотра этой информации: с помощью утилиты stat и debugfs. Но первый способ подойдет не для всех дистрибутивов Linux. Второй способ – универсальный, но не такой простой в использовании. Разберемся с каждым из них по отдельности.

1. С помощью stat

Утилита stat выводит подробные сведения о файле. В том числе выводится дата создания файла Linux. Для ее запуска в терминале достаточно указать путь к файлу. Для примера посмотрим информацию про изображение pic_1.jpeg, хранящееся в каталоге /home/root-user/Pictures:

w+IiqFOkD0yMwAAAABJRU5ErkJggg==

Нужная информация записана в графе Создан. А с помощью опции -c получится задать определенные правила форматирования для вывода информации, например, оставив только нужную графу:

stat -c ‘%w’ /home/root-user/Pictures/pic_1.jpeg

wfg1axWkj0EwAAAAABJRU5ErkJggg= https://losst.pro/komanda-stat-v-linux

отдельной статье. Можете с ней ознакомиться.

2. С помощью debugfs

В отличие от утилиты stat, описанной в предыдущем разделе, у debugfs нет таких ограничений по версии. А значит, она будет работать всегда. Но и процедура использования у нее несколько более запутанная. Связано это с тем, что для просмотра даты создания файла через debugfs, нужно узнать номер его inode и файловую систему. Получить inode выйдет с помощью команды ls с опцией -i, указав путь к файлу:

ls -i /home/root-user/scripts/main_script.txt

kbjuEEK5LbK0K6LuAsQU4ZIWsXLUz9ZvcooY+rQ40HYtXfCCLOPe4xkiUvQHr092rnlO55aeZHmA0j6PD4BqQdBLtv8ej9TnrMPYvPVcUVz37alePamcD+sGl9ulKrXsee+ZPv8vdbZpu5IaHMAAAAAASUVORK5CYII=

А для просмотра файловой системы пригодится команда df:

CwwxO5M5TnclAAAAAElFTkSuQmCC

Теперь все нужные данные собраны, и можно переходить к использованию утилиты debugfs. Ей нужно передать опцию -R, указать номер inode, а затем название файловой системы:

sudo debugfs -R ‘stat ‘ /dev/sda5

UvBimUNcruQAAAAASUVORK5CYII https://losst.pro/wp-content/uploads/2022/03/data-sozdaniya-fayla-v-linux-8.png8BecyCvZGa4qkAAAAASUVORK5CYII=

Подробное разъяснение о том, что такое inode, есть в специальной статье на нашем сайте.

Выводы

Мы разобрали два способа посмотреть дату создания файла Linux. Утилита stat несколько более удобная, ведь для нее достаточно указать только путь к нему. Но она не будет отображать нужную информацию до версии 8.31 GNU coreutils. А debugfs в этом плане более универсальная, но не такая простая в использовании. Ведь для получения данных она требует ввода номера inode файла и его файловую систему.

Читайте также:  Lima linux on mac

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

How to get file creation date in Linux?

I am working with batches of files that contain information about the same object at the different times of its life, and the only way to order them is by creation date. I was using this:

//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; 

But that does not seems to work. What am I doing wrong? Are there other, more reliable/simple ways to get file creation date under Linux?

fstat doesn’t fetch a «file created» timestamp value because many filesystems don’t track that data. What filesystem are you working with?

One that is standard for latest Ubuntu desktop, i suppose — i am running my code on the virtual machine (vmware player, to be exact), and left all details like filesystem to ubuntu installer.

If that code compiled without warnings, you have a major problem with your compiler. If that code compiled with warnings, learn to pay heed to warnings about incorrect argument types (or pointer to integer conversions) and fix the code so it compiles without warnings.

5 Answers 5

The nearest approximation to ‘creation date’ is the st_ctime member in the struct stat , but that actually records the last time the inode changed. If you create the file and never modify its size or permissions, that works as a creation time. Otherwise, there is no record of when the file was created, at least in standard Unix systems.

For your purposes, sort by st_mtime . or get the files named with a timestamp in the name.

Note that if you are on Darwin (Mac OS X), the creation time is available. From the man page for stat(2) :

However, when the macro _DARWIN_FEATURE_64_BIT_INODE is defined, the stat structure will now be defined as:

Note the st_birthtimespec field. Note, too, that all the times are in struct timespec values, so there is sub-second timing ( tv_nsec gives nanosecond resolution). POSIX 2008 requires the struct timespec time keeping on the standard times; Darwin follows that.

Sadly, the files are created by another application. Sadly, i haven’t got permissions to change anything about it.

fstat works on file descriptors, not FILE structures. The simplest version:

#include #include #include #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; ireturn 0; > 

You will need to figure out if your system has st_birthtime in its stat structure by inspecting sys/stat.h or using some kind of autoconf construct.

Читайте также:  Линукс открыть терминал комбинация

@srv19 You can get the file descriptor by using open(2) or by using fileno(tf). What I’ve given you however is a way to inspect it’s attributes without having to open the file. If you need to open the file anyway and want to use stdio functions, then fileno is your friend.

Your solution got rid of my problem. Thanks a lot. I’ve suspected i was mission something in the usage of fstat.

File creation time is not stored anywhere, you can only retrieve one of the following:

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 */ 

Your code should give you the last modification time, however. Note: you can use stat() instead of fstat() without opening the file ( stat() takes the file name as param).

To get the file creation date in linux, I use the following method

root@sathishkumar# cat 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 ' /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: Last time file was opened or executed

ctime: Time the inode information was updated. ctime also gets updated when file is modified

crtime: File creation time

Источник

Get file created/creation time? [duplicate]

Is there a command in Linux which displays when the file was created ? I see that ls -l gives the last modified time, but can I get the created time/date?

Even while «OT» as this is asking for a tool to display this information, I think it’s a valuable thing for programmers to know when dealing with more UNIX-y filesystems.

The command is sudo debugfs -R ‘stat /path/to/file’ /dev/sdaX (replace sdaX with the device name of the filesystem on which the file resides). The creation time is the value of crtime . You can add | grep .[^ca]time to list just mtime (the modification time) and crtime (the creation time).

Some of the answers here are nearly 11 years old, and are no longer correct. This top-voted answer is recently edited/updated, and worth a look. Also — if you’re interested in sorting your ls output the Possible Duplicate also has an up-to-date answer that reflects our current systems’ status.

Читайте также:  Линукс убунту командная строка

3 Answers 3

The stat command may output this — (dash). I guess it depends on the filesystem you are using. stat calls it the «Birth time». On my ext4 fs it is empty, though.

%w Time of file birth, human-readable; — if unknown

%W Time of file birth, seconds since Epoch; 0 if unknown

stat foo.txt File: `foo.txt' Size: 239 Blocks: 8 IO Block: 4096 regular file Device: 900h/2304d Inode: 121037111 Links: 1 Access: (0644/-rw-r--r--) Uid: ( 1000/ adrian) Gid: ( 100/ users) Access: 2011-10-26 13:57:15.000000000 -0600 Modify: 2011-10-26 13:57:15.000000000 -0600 Change: 2011-10-26 13:57:15.000000000 -0600 Birth: - 

Источник

How to get file creation date/time in Bash/Debian?

I’m using Bash on Debian GNU/Linux 6.0. Is it possible to get the file creation date/time? Not the modification date/time. ls -lh a.txt and stat -c %y a.txt both only give the modification time.

13 Answers 13

Unfortunately your quest won’t be possible in general, as there are only 3 distinct time values stored for each of your files as defined by the POSIX standard (see Base Definitions section 4.8 File Times Update)

Each file has three distinct associated timestamps: the time of last data access, the time of last data modification, and the time the file status last changed. These values are returned in the file characteristics structure struct stat, as described in .

EDIT: As mentioned in the comments below, depending on the filesystem used metadata may contain file creation date. Note however storage of information like that is non standard. Depending on it may lead to portability problems moving to another filesystem, in case the one actually used somehow stores it anyways.

Such sad news. It’d be so useful right now to determine easily whether a file has been deleted and recreated or has been there all along.

Do you know how that works on a Mac? The Finder shows three timestamps as ‘Created’, ‘Modified’, ‘Last openend’.

ls -i file #output is for me 68551981 debugfs -R 'stat ' /dev/sda3 # /dev/sda3 is the disk on which the file exists #results - crtime value [root@loft9156 ~]# debugfs -R 'stat ' /dev/sda3 debugfs 1.41.12 (17-May-2010) Inode: 68551981 Type: regular Mode: 0644 Flags: 0x80000 Generation: 769802755 Version: 0x00000000:00000001 User: 0 Group: 0 Size: 38973440 File ACL: 0 Directory ACL: 0 Links: 1 Blockcount: 76128 Fragment: Address: 0 Number: 0 Size: 0 ctime: 0x526931d7:1697cce0 -- Thu Oct 24 16:42:31 2013 atime: 0x52691f4d:7694eda4 -- Thu Oct 24 15:23:25 2013 mtime: 0x526931d7:1697cce0 -- Thu Oct 24 16:42:31 2013 **crtime: 0x52691f4d:7694eda4 -- Thu Oct 24 15:23:25 2013** Size of extra inode fields: 28 EXTENTS: (0-511): 352633728-352634239, (512-1023): 352634368-352634879, (1024-2047): 288392192-288393215, (2048-4095): 355803136-355805183, (4096-6143): 357941248-357943295, (6144 -9514): 357961728-357965098 

Источник

Оцените статью
Adblock
detector