//------------------------------------------------------------------- // statdemo.cpp // // This program illustrates the 'stat()' library-function if a // user supplies a file-object's pathname on the command-line. // // to compile: $ g++ statdemo.cpp -o statdemo // to execute: $ ./statdemo // // programmer: ALLAN CRUSE // written on: 06 APR 2009 //------------------------------------------------------------------- #include // for ctime() #include // for printf(), perror() #include // for exit() #include // for strncat() #include // for stat() void strmode( mode_t mode, char *str ); int main( int argc, char **argv ) { // allow a user to specify the file-object's pathname char pathname[ 128 ] = { 0 }; if ( argc == 1 ) strcat( pathname, "." ); else strncat( pathname, argv[ 1 ], 127 ); // obtain the object's type, size, and access attributes struct stat info = { 0 }; if ( stat( pathname, &info ) < 0 ) { perror( "stat" ); exit(1); } // convert some items to a humanly readable format char prot[ 12 ] = { 0 }; strmode( info.st_mode, prot ); int major = info.st_rdev / 0x100; int minor = info.st_rdev % 0x100; // display the information in the 'struct stat' object printf( "\n stat \'%s\' \n\n", pathname ); printf( " st_dev = %d \n", info.st_dev ); printf( " st_ino = %d \n", info.st_ino ); printf( " st_mode = %s \n", prot ); printf( " st_nlink = %d \n", info.st_nlink ); printf( " st_uid = %d \n", info.st_uid ); printf( " st_gid = %d \n", info.st_gid ); printf( " st_rdev = (%d,%d) \n", major, minor ); printf( " st_size = %0d \n", info.st_size ); printf( " st_blksize = %d \n", info.st_blksize ); printf( " st_blocks = %d \n", info.st_blocks ); printf( " st_atime = %s", ctime( &info.st_atime ) ); printf( " st_mtime = %s", ctime( &info.st_mtime ) ); printf( " st_ctime = %s", ctime( &info.st_ctime ) ); printf( "\n" ); } char filetypeletter( mode_t mode ) { if ( S_ISREG( mode ) ) return '-'; if ( S_ISDIR( mode ) ) return 'd'; if ( S_ISBLK( mode ) ) return 'b'; if ( S_ISCHR( mode ) ) return 'c'; if ( S_ISLNK( mode ) ) return 'l'; if ( S_ISFIFO( mode ) ) return 'p'; if ( S_ISSOCK( mode ) ) return 's'; return '?'; } void strmode( mode_t mode, char *str ) { str[ 0 ] = filetypeletter( mode ); str[ 1 ] = mode & S_IRUSR ? 'r' :'-'; str[ 2 ] = mode & S_IWUSR ? 'w' :'-'; str[ 3 ] = (mode & S_ISUID ? (mode & S_IXUSR ? 's' :'S') : (mode & S_IXUSR ? 'x' : '-')); str[ 4 ] = mode & S_IRGRP ? 'r' :'-'; str[ 5 ] = mode & S_IRGRP ? 'w' :'-'; str[ 6 ] = (mode & S_ISGID ? (mode & S_IXGRP ? 's' :'S') : (mode & S_IXGRP ? 'x' : '-')); str[ 7 ] = mode & S_IROTH ? 'r' :'-'; str[ 8 ] = mode & S_IROTH ? 'w' :'-'; str[ 6 ] = (mode & S_ISVTX ? (mode & S_IXOTH ? 't' :'T') : (mode & S_IXOTH ? 'x' : '-')); str[ 10 ] = ' '; str[ 11 ] = '\0'; } // NOTE: Our code for the 'strmode()' function used here is adapted from // a more general routine posted online by the Free Software Foundation.