Skip to content

Instantly share code, notes, and snippets.

@ChronoMonochrome
Last active June 7, 2020 19:45
Show Gist options
  • Save ChronoMonochrome/7603684fa3d149570a11dd33110a6319 to your computer and use it in GitHub Desktop.
Save ChronoMonochrome/7603684fa3d149570a11dd33110a6319 to your computer and use it in GitHub Desktop.
count words in multiple files (C)
/*
* File: driver2.c
* YOUR NAME ... YOU NEED TO IMPLEMENT THE FUNCTIONS HERE....
*
* ....
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "myio.h"
char *removeSpaces(char *input);
int countWordsSingleFile(char *fileName);
int countWords(char *str);
int main(int argc, char *argv[])
{
pid_t childPid, wpid;
int status = 0;
int totalCount = 0;
if (argc < 2) {
perror("Usage: driver2 input_file.txt");
return -EINVAL;
}
//Father code (before child processes start)
for (int id = 1; id < argc; id++) {
if ((childPid = fork()) == 0) {
//child code
totalCount = countWordsSingleFile(argv[id]);
if (totalCount > 0)
printf("Child process %d for file %s: totalCount=%d\n", childPid, argv[id], totalCount);
else if (totalCount == -ENOENT)
printf("Child process %d for file %s: file doesn't exist\n", childPid, argv[id]);
exit(0);
}
}
while ((wpid = wait(&status)) > 0); // this way, the father waits for all the child processes
//Father code (After all child processes end)
return 0;
}
int countWordsSingleFile(char *fileName) {
FILE *fp;
char *str;
char *newstr;
int count = 0;
int total_count = 0;
/* opening file for reading */
fp = fopen(fileName, "r");
if (fp == NULL) {
//perror("Error opening file");
return -ENOENT;
}
while (str = ReadLineFile(fp)) {
/* writing content to stdout */
if (str[0] == '\0')
break;
newstr = removeSpaces(str);
count = countWords(str);
//printf("count=%d, str=%s\n", count, newstr);
total_count+=count;
free(str);
free(newstr);
}
fclose(fp);
return total_count;
}
#define OUT 0
#define IN 1
// returns number of words in str
int countWords(char *str)
{
int state = OUT;
int wc = 0; // word count
// Scan all characters one by one
while (*str)
{
// If next character is a separator, set the
// state as OUT
if (*str == ' ' || *str == '\n' || *str == '\t')
state = OUT;
// If next character is not a word separator and
// state is OUT, then set the state as IN and
// increment word count
else if (state == OUT)
{
state = IN;
++wc;
}
// Move to next character
++str;
}
return wc;
}
char *removeSpaces(char *input) {
int i = 0, j, n = strlen(input);
while (i < n)
{
if(((input[i]==' ') && (input[i+1] == ' ' || input[i-1] == ' ')) ||
((input[i]==' ') && i == n-2)||
((i == 0) && (input[i]==' ')))
{
for(j=i; j<n; j++)
input[j]=input[j+1];
n--;
}
else
{
i++;
}
}
n = strlen(input);
if (input[n-1] != '\n')
input[n] = '\n';
return strdup(input);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment