/* OpSys Spring 2005 Sample program that calls stat() Usage: ./showfileattr filename calls stat() on the file specified on the command line and prints out information about the file. For reference, here is the definition of struct stat struct stat { dev_t st_dev; device ino_t st_ino; inode mode_t st_mode; protection nlink_t st_nlink; number of hard links uid_t st_uid; user ID of owner gid_t st_gid; group ID of owner dev_t st_rdev; device type (if inode device) off_t st_size; total size, in bytes blksize_t st_blksize; blocksize for filesystem I/O blkcnt_t st_blocks; number of blocks allocated time_t st_atime; time of last access time_t st_mtime; time of last modification time_t st_ctime; time of last change }; */ #include #include #include #include /* exit */ #include /* errno */ #include /* strerror */ #include /* ctime */ /* showfile calls stat on the filename passed in and prints out the value of some of the fields in the struct stat filled in. */ void showfile( const char *filename ) { struct stat sbuf; if (stat(filename,&sbuf)==-1) { /* stat returned an error! */ fprintf(stderr,"Error stating file %s: %s\n",filename, strerror(errno)); return; } printf("Information about %s\n",filename); if (S_ISREG(sbuf.st_mode)) { /* This is a regular file */ printf("\tType: Regular File\n"); } else if (S_ISDIR(sbuf.st_mode)) { /* This is a directory */ printf("\tType: Directory\n"); } else { /* could be a number of other things... */ printf("\tType: something other than regular file or directory...\n"); } printf("\tOwner: %d\n",(int) sbuf.st_uid); printf("\tSize: %d\n",(int) sbuf.st_size); /* actual usage is # 512 byte blocks */ printf("\tDisk space used: %d\n",512 * (int)sbuf.st_blocks); printf("\tLast access: %s",ctime(&sbuf.st_atime)); printf("\tLast modification: %s",ctime(&sbuf.st_mtime)); printf("\tLast status change: %s",ctime(&sbuf.st_ctime)); } int main(int argc, char **argv) { if (argc<2) { printf("You have to tell me what file!\n"); exit(1); } showfile(argv[1]); return(0); }