Advertisement
Guest User

wc.c

a guest
Jun 17th, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.59 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/types.h>
  4. #include <sys/wait.h>
  5. #include <sys/stat.h>
  6. #include <fcntl.h>
  7. #include <unistd.h>
  8. #include <ctype.h>
  9. #include <signal.h>
  10.  
  11. int is_end_of_sentence(char c) {
  12.     return c == '.' || c == '?' || c == '!';
  13. }
  14.  
  15. void wc(char *filename) {
  16.     int fd = open(filename, O_RDONLY);
  17.  
  18.     if(fd < 0) {
  19.         perror("open");
  20.         return;
  21.     }
  22.  
  23.     int sentences_count = 0, word_count = 0, char_count = 0;
  24.  
  25.     char data[100];
  26.  
  27.     ssize_t read_value = read(fd, data, 100);
  28.     if(read_value < 0) {
  29.         perror("read");
  30.         return;
  31.     }
  32.  
  33.     while(read_value != 0) {
  34.         for(int i = 0; i < read_value; i++) {
  35.             if(isspace(data[i])) {
  36.                 word_count++;
  37.             } else if(is_end_of_sentence(data[i])) {
  38.                 sentences_count++;
  39.             }
  40.  
  41.             char_count++;
  42.         }
  43.  
  44.         read_value = read(fd, data, 100);
  45.         if(read_value < 0) {
  46.             perror("read");
  47.             return;
  48.         }
  49.     }
  50.  
  51.     printf("%d %d %d %s\n", sentences_count, word_count, char_count, filename);
  52.  
  53.     if(close(fd) < 0) {
  54.         perror("close");
  55.         return;
  56.     }
  57. }
  58.  
  59. int main(int argc, char **argv) {
  60.     pid_t pid;
  61.     for(int i = 1; i < argc; i++) {
  62.         pid = fork();
  63.         if(pid < 0) {
  64.             perror("fork");
  65.             return -1;
  66.         }
  67.  
  68.         if(pid == 0) {
  69.             wc(argv[i]);
  70.         } else {
  71.             int *status = NULL;
  72.             waitpid(pid, status, 0);
  73.             return 0;
  74.         }
  75.     }
  76.  
  77.     return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement