Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <ctype.h>
- #include <signal.h>
- int is_end_of_sentence(char c) {
- return c == '.' || c == '?' || c == '!';
- }
- void wc(char *filename) {
- int fd = open(filename, O_RDONLY);
- if(fd < 0) {
- perror("open");
- return;
- }
- int sentences_count = 0, word_count = 0, char_count = 0;
- char data[100];
- ssize_t read_value = read(fd, data, 100);
- if(read_value < 0) {
- perror("read");
- return;
- }
- while(read_value != 0) {
- for(int i = 0; i < read_value; i++) {
- if(isspace(data[i])) {
- word_count++;
- } else if(is_end_of_sentence(data[i])) {
- sentences_count++;
- }
- char_count++;
- }
- read_value = read(fd, data, 100);
- if(read_value < 0) {
- perror("read");
- return;
- }
- }
- printf("%d %d %d %s\n", sentences_count, word_count, char_count, filename);
- if(close(fd) < 0) {
- perror("close");
- return;
- }
- }
- int main(int argc, char **argv) {
- pid_t pid;
- for(int i = 1; i < argc; i++) {
- pid = fork();
- if(pid < 0) {
- perror("fork");
- return -1;
- }
- if(pid == 0) {
- wc(argv[i]);
- } else {
- int *status = NULL;
- waitpid(pid, status, 0);
- return 0;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement