CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Finding the attributes of a file

As seen in Lecture-15, many operating systems manage their data in a file system, in particular maintaining files in a hierarchical directory structure - directories contain files and other (sub)directories.

As we saw with time-based information, we may request file- and directory information from the operating system by calling system-calls. We may employ another POSIX function, stat(), and the system-provided structure struct stat, to determine the attributes of each file:

#include  <stdio.h>
#include  <stdlib.h>
#include  <sys/types.h>
#include  <sys/stat.h>
#include  <time.h>
#include  <unistd.h>

char *progname;

void file_attributes(char *filename)
{
  struct stat  stat_buffer;

  if(stat(filename, &stat_buffer) != 0) {  // can we 'stat' the file's attributes?
    perror( progname );
    exit(EXIT_FAILURE);
  }
  else if( S_ISREG( stat_buffer.st_mode ) ) {
    printf( "%s is a regular file\n", filename );
    printf( "is %i bytes long\n", (int)stat_buffer.st_size );
    printf( "and was last modified on %i\n", (int)stat_buffer.st_mtime);

    printf( "which was %s", ctime( &stat_buffer.st_mtime) );
  }
}

POSIX is an acronym for "Portable Operating System Interface", a family of standards specified by the IEEE for maintaining compatibility between operating systems. POSIX defines the application programming interface (API), along with command line shells and utility interfaces, for software compatibility with variants of Unix (such as macOS and Linux) and other operating systems (e.g. Windows has a POSIX emulation layer).

 


CITS2002 Systems Programming, Lecture 16, p5, 19th September 2023.