简体   繁体   中英

How to get the oldest file in a directory using C?

I'm implementing log mechanism and I want to delete oldest log file based on time creating in the directory when reach the defined size.

But now I stuck on getting the oldest file based on time creating. How to get it using C?

There isn't a portable way to get a file's creation time (or its modification time) in C.

Instead you need to rely on something that isn't strictly portable - eg use the file name from the directory entry with the stat() function defined by POSIX, to get a structure that might or might not have a struct timespec st_ctim; field.

Of course some file systems don't have a creation time at all; and even if there is one if you copy a file elsewhere (eg to remote storage) the creation time will be gone, so it's relatively unreliable.

Instead; it's much better to put the creation time and date into the file name. If you do this in the correct order ("year, month, day, hour, minute, second" - eg maybe like " mylog_2019-10-31_14-23-45.txt ") and keep leading zeros (eg 09 for month and never 9 for month) then sorting a list of file names alphanumerically will also sort them chronologically.

you should maintain an internal queue of file name. New one created is added to the head constantly. When need delete, let delete the tail guy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM