Advertisement
Tavi33

SO #4 v2

Oct 18th, 2016
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.14 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <fcntl.h>
  4. #include <string.h>
  5. #include <sys/types.h>
  6. #include <sys/stat.h>
  7. #include <unistd.h>
  8.  
  9. int main(int argc, char *args[]) {
  10.     if(argc != 3) {
  11.       printf("Usage: %s <file> <output directory>\n", args[0]);
  12.       exit(1);
  13.     }
  14.     struct stat st;
  15.  
  16.     char buffer[20];
  17.     char *output_dir;
  18.     output_dir = (char *) malloc((sizeof(args[2])+sizeof(args[1]))*sizeof(char));
  19.    
  20.     strcat(output_dir, args[2]);
  21.     strcat(output_dir, "/");
  22.     strcat(output_dir, args[1]);
  23.    
  24.    
  25.     int file = open(args[1], O_RDONLY, S_IRUSR|S_IWUSR);
  26.     if(file == -1) {
  27.       printf("Could not open input file\n");
  28.     }
  29.    
  30.     int digit_count = 0;
  31.     int even_digit_count = 0;
  32.  
  33.     while(read(file, buffer, sizeof(buffer))) {
  34.       int i;
  35.       for(i=0; buffer[i]; i++) {
  36.     if(isdigit(buffer[i])) {
  37.       digit_count++;
  38.       if((int)(buffer[i]-'0') % 2 == 0) {
  39.         even_digit_count++;
  40.       }
  41.     }
  42.       }
  43.     }
  44.     char report_string[128];
  45.    
  46.     if (stat(args[1], &st) == -1) {
  47.         printf("Error while getting stat!\n");
  48.         exit(1);
  49.     }
  50.  
  51.     sprintf(report_string, "File owner GID: %d | Digit count: %d | Even digit count: %d\n", (int) st.st_gid, digit_count, even_digit_count);
  52.    
  53.     close(file);
  54.     file = open(output_dir, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR);
  55.     if(file == -1) {
  56.       printf("Error while opening output file!\n");
  57.       exit(1);
  58.     }
  59.     if(write(file, report_string, strlen(report_string)/sizeof(char)) == -1) {
  60.       printf("Error while writing report!\n");
  61.       exit(1);
  62.     }
  63.     char cur_dir[128];
  64.     if(getcwd(cur_dir, sizeof(cur_dir)) == NULL) {
  65.       printf("Error while getting CWD!\n");
  66.       exit(1);
  67.     }
  68.     strcat(cur_dir, "/slink-");
  69.     strcat(cur_dir, args[1]);
  70.     unlink(cur_dir);
  71.     if(symlink(output_dir, cur_dir) == -1) {
  72.       printf("Error while creating symlink!\n");
  73.       exit(1);
  74.     }
  75.     if (stat(cur_dir, &st) == -1) {
  76.         printf("Error while getting stat!\n");
  77.         exit(1);
  78.     }
  79.     printf("Size for simlink: %d\n", st.st_size);
  80.     printf("Report generated\n");
  81.     exit(0);
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement