Advertisement
Tavi33

SO #4

Oct 18th, 2016
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.40 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <fcntl.h>
  4. #include <string.h>
  5.  
  6. int main(int argc, char *args[]) {
  7.     if(argc != 3) {
  8.       printf("Usage: %s <file> <output directory>\n", args[0]);
  9.       exit(1);
  10.     }
  11.     char buffer[20];
  12.     char *output_dir;
  13.     output_dir = (char *) malloc((sizeof(args[2])+sizeof(args[1]))*sizeof(char));
  14.    
  15.     strcat(output_dir, args[2]);
  16.     strcat(output_dir, "/");
  17.     strcat(output_dir, args[1]);
  18.    
  19.    
  20.     int file = open(args[1], O_RDONLY, S_IRUSR|S_IWUSR);
  21.     if(file == -1) {
  22.       printf("Could not open input file\n");
  23.     }
  24.    
  25.     int digit_count = 0;
  26.     int even_digit_count = 0;
  27.  
  28.     while(read(file, buffer, sizeof(buffer))) {
  29.       int i;
  30.       for(i=0; buffer[i]; i++) {
  31.     if(isdigit(buffer[i])) {
  32.       digit_count++;
  33.       if((int)(buffer[i]-'0') % 2 == 0) {
  34.         even_digit_count++;
  35.       }
  36.     }
  37.       }
  38.     }
  39.     char report_string[128];
  40.     sprintf(report_string, "Digit count: %d | Even digit count: %d\n", digit_count, even_digit_count);
  41.     close(file);
  42.     file = open(output_dir, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR);
  43.     if(file == -1) {
  44.       printf("Error while opening output file!\n");
  45.       exit(1);
  46.     }
  47.     if(write(file, report_string, strlen(report_string)/sizeof(char)) == -1) {
  48.       printf("Error while writing report!\n");
  49.       exit(1);
  50.     }
  51.     printf("Report generated\n");
  52.     exit(0);
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement