Search code examples
common-lisp

How to get a file size (and other attributes) in Common Lisp?


How do we get file attributes ? I primarily am looking to get the size, but also its last access time and other attributes.

I only found (file-length some-file) that gets a stream so is used this way:

(with-open-file (file "some file name") 
  (file-length file))

Looks to be doing the job but:

  • it gets a stream: this is uncoherent with the rest of the api
  • there really are no shorter function ??
  • (is it the most efficient way to do ?)

I see nothing related to a file length or attributes in Osicat. Maybe is it its role and I'll fill a feature request ?

Practical CL talks about file-length and refers to Osicat and that's it.

No more info on the CL cookbook, no more "posix" or "file" related material on the awesome-cl list.

I would appreciate something like in elisp.

thanks

edit: maybe on iolib but it looks like its online doc is uncomplete and not talking about files even though it announces to having "a pathname library and file-system utilities". But apparently it does not have do what I'm looking for: https://github.com/sionescu/iolib/blob/master/src/os/os-unix.lisp


Solution

  • With Osicat, you call stat on the file and you get a bunch of things in a structure:

    (describe (osicat-posix:stat #P"/tmp/file"))
    
    #<OSICAT-POSIX:STAT {1004F20C93}>
      [standard-object]
    
    Slots with :INSTANCE allocation:
      DEV      = 2065
      INO      = 7349974
      MODE     = 33204
      NLINK    = 1
      UID      = 1000
      GID      = 1000
      RDEV     = 0
      SIZE     = 4304
      BLKSIZE  = 4096
      BLOCKS   = 16
      ATIME    = 1497626097
      MTIME    = 1497347216
      CTIME    = 1497347216
    ; No value
    

    You can access the different slots with the following functions :

    osicat-posix:stat-dev
    osicat-posix:stat-gid                        
    osicat-posix:stat-ino                        
    osicat-posix:stat-uid                        
    osicat-posix:stat-mode                       
    osicat-posix:stat-rdev                       
    osicat-posix:stat-size                       
    osicat-posix:stat-atime                      
    osicat-posix:stat-ctime                      
    osicat-posix:stat-mtime                      
    osicat-posix:stat-nlink                      
    osicat-posix:stat-blocks                     
    osicat-posix:stat-blksize