| 1 | #include <stdio.h> |
| 2 | #include <stdlib.h> |
| 3 | #include <errno.h> |
| 4 | #include <string.h> |
| 5 | #include <pwd.h> |
| 6 | |
| 7 | #include <sys/types.h> |
| 8 | #include <sys/stat.h> |
| 9 | |
| 10 | int main(int argc, char *argv[]) { |
| 11 | |
| 12 | struct stat file_stat; |
| 13 | struct passwd *file_pd; |
| 14 | |
| 15 | int argc_decr; |
| 16 | mode_t *ft; |
| 17 | |
| 18 | extern int errno; |
| 19 | |
| 20 | argc_decr = argc; /* K&R 117(ยง5.10) warns against decrementing argc directly */ |
| 21 | |
| 22 | if(argc <= 1 || argc >= 5) { |
| 23 | |
| 24 | printf("USAGE: %s <file> [-o, -c]\n", argv[0]); |
| 25 | return 1; |
| 26 | |
| 27 | } else if(stat(argv[1], &file_stat)) { |
| 28 | |
| 29 | if(errno == ENOENT) |
| 30 | printf("provided file does not exist.\n"); |
| 31 | else if(errno == EACCES) |
| 32 | printf("improper permissions to read from file.\n"); |
| 33 | else if(errno == ENAMETOOLONG) |
| 34 | printf("provided path is too long.\n"); |
| 35 | else if(errno == ENOTDIR) |
| 36 | printf("provided path contains a non-existant directory.\n"); |
| 37 | else if(errno == EOVERFLOW) |
| 38 | printf("provided file cannot be properly contained into a stat buf.\n"); |
| 39 | else if(errno == ELOOP) |
| 40 | printf("provided file points to an irresolvable symlink chain.\n"); |
| 41 | |
| 42 | return errno; |
| 43 | } |
| 44 | |
| 45 | printf("file size in bytes: %llu\n", file_stat.st_size); |
| 46 | |
| 47 | while(argc_decr > 2) { |
| 48 | |
| 49 | if(!strncmp(argv[argc_decr - 1], "-o", 5)) { |
| 50 | |
| 51 | if((file_pd = getpwuid(file_stat.st_uid)) != NULL) |
| 52 | printf("file owned by user %s.\n", file_pd->pw_name); |
| 53 | |
| 54 | else |
| 55 | printf("file owned by uid %d.\n", file_stat.st_uid); |
| 56 | |
| 57 | } else if(!strncmp(argv[argc_decr - 1], "-t", 5)) { |
| 58 | |
| 59 | printf("file is a "); |
| 60 | ft = &(file_stat.st_mode); |
| 61 | |
| 62 | if (S_ISBLK(*ft)) printf("block device.\n"); |
| 63 | else if(S_ISCHR(*ft)) printf("character device.\n"); |
| 64 | else if(S_ISFIFO(*ft)) printf("fifo pipe.\n"); |
| 65 | else if(S_ISREG(*ft)) printf("regular file.\n"); |
| 66 | else if(S_ISDIR(*ft)) printf("directory.\n"); |
| 67 | else if(S_ISLNK(*ft)) printf("symbolic link.\n"); |
| 68 | |
| 69 | |
| 70 | } else { |
| 71 | |
| 72 | printf("provided argument is invalid, must be '-t' or '-o'.\n"); |
| 73 | return 1; |
| 74 | } |
| 75 | |
| 76 | argc_decr--; |
| 77 | } |
| 78 | |
| 79 | return 0; |
| 80 | } |