一、概述
Linux ctime,即 Change Time,是指 Linux 文件系統記錄每個文件或目錄的最近狀態更改時間,也就是說,當文件或目錄的權限、所有權、內容等發生更改時,其 ctime 屬性就會被更新。與之相似的還有 access time 和 modification time
二、 ctime 屬性分析
1. 創建文件、修改屬性
當文件或目錄被創建時,他們的 ctime 屬性會被設置為當前時間。具體的實現是在 ext3、ext4、xfs 等文件系統的 inode 中的 i_ctime 字段記錄下這個時間。當文件或目錄的某些屬性被修改時,如權限、所有權等,也會使其 ctime 屬性被更新。
#include #include int main() { const char* path = "/path/to/file"; struct stat file_stat; stat(path, &file_stat); printf("ctime: %ld\n", file_stat.st_ctime); return 0; }
2. 文件內容修改
如果文件或目錄的內容被修改,則其 ctime 屬性依然會被更新,但需注意的是,當文件內容被修改,但該文件不保存在內存中時,操作系統會將該文件從磁盤中讀取到內存中,此時的 ctime 是讀取時間而非修改時間。
#include #include #include #include #include int main() { const char* path = "/path/to/file"; struct stat file_stat; int fd; fd = open(path, O_RDWR); write(fd, "hello world", 11); stat(path, &file_stat); printf("ctime: %ld\n", file_stat.st_ctime); close(fd); return 0; }
3. 刪除文件或目錄
當文件或目錄被刪除時,其 ctime 屬性會被修改,但這個時間並不是文件或目錄真正被刪除的時間,而是它的目錄的 mtime 字段所記錄的時間,原因是 Linux 文件系統將每個文件或目錄都看作是目錄樹的一個節點,當節點的文件或目錄被刪除時,該節點所在的目錄的 mtime 就可以被更新。
#include #include int main() { const char* path = "/path/to/file"; int ret; ret = unlink(path); if (ret == 0) { printf("File %s is deleted successfully.\n", path); } else { printf("Failed to delete file %s.\n", path); } return 0; }
三、小結
實際上,ctime 是文件或目錄的狀態修改時間,而不是內容修改時間,它包括了文件或目錄的創建、屬性更新和刪除時間等。了解 ctime 的特點與用法,對於 Linux 文件系統管理和調試都是非常重要的。
原創文章,作者:WAFQS,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/333252.html