Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //string.h is used for puts, while stdlib is used for malloc/realloc
- //and ctype for isalnum and ispunct.
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <ctype.h>
- //function that checks if malloc and realloc succeed.
- void memCheck(char *str);
- //main function.
- int main(int argc, char *argv[])
- {
- //str is the string used to hold the contents of the file.
- //ch temporarily holds the char being read from the file before it gets but in str.
- //fp is the pointer to input stream from the file named in filename.
- //x, y, z are counters. x for chars, y for words, and z for lines.
- char *str, ch;
- FILE *fp;
- int x = 0, y = 0, z = 0;
- //tests for valid arguments.
- if (argc-2)
- {
- puts("Invalid arguments. Usage: ./daniel_sawyer_hw07 NameOfFile.txt\nTry again.\n");
- return 0;
- }
- //it opens the file stream and checks to make sure the file is in the correct location.
- fp = fopen(argv[1], "r");
- if (fp == NULL)
- {
- puts("Invalid file. Usage: ./daniel_sawyer_hw07 NameOfFile.txt\nMake sure file is in same direcotry as binary and try again.\n");
- return 0;
- }
- //allocates memory for the str pointer effectively turning it into a char array size 1 and tests if its successful.
- str = malloc(sizeof(char));
- memCheck(str);
- //loop that reads every char in the input file and counts all the chars, words, and lines that are in the file.
- while ((ch = getc(fp)) != EOF)
- {
- //counts words and lines. if previous character was alpha/num or punctuation, it increments the word variable y.
- //also counts lines (z) everytime the \n char is detected.
- switch(ch)
- {
- case ' ' : if ( isalnum(str[x-1]) || ispunct(str[x-1]) ) ++y; break;
- case '\n' : if ( isalnum(str[x-1]) || ispunct(str[x-1]) ) ++y; ++z; break;
- }
- //reallocates memory for the string to x+1 chars and then checks if allocation was successful.
- str = realloc(str, (x+1) * sizeof(char));
- memCheck(str);
- //puts the char in the string then increments x.
- str[x++] = ch;
- }
- //closes file stream since it is no longer needed.
- fclose(fp);
- //increments z to the correct number of lines.
- ++z;
- //checks to make sure the last char was alpha/num or punctuation.
- //if it is, it increments y (words) to the correct amount.
- if ( isalnum(str[x-1]) || ispunct(str[x-1]) )
- ++y;
- //prints the number of chars, words, and lines in the input file.
- printf("\nNumber of Characters: %d\n", x);
- printf("\nNumber of Words: %d\n", y);
- printf("\nNumber of Lines: %d\n", z);
- //ends program.
- return 0;
- }
- //memory check function. if mem runs out, kills program.
- void memCheck(char *str)
- {
- if (str == NULL)
- {
- puts("Memory allocation failed. Please try again.\n");
- exit(EXIT_FAILURE);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement