Here's my code:
#include <stdio.h>
#include <stdlib.h>
enum {out, in}; /* In this case enum is more appropriate than bool */
void wordCount (FILE* myFile)
{
int myChar, wordNumber, state;
/* Initializing variables */
myChar = 0;
wordNumber = 0;
state = out; /* Starting out of a word */
while ((myChar = fgetc(myFile)) != EOF)
{
printf("%c", myChar);
if (myChar == ' ' || myChar == '\t' || myChar == '\n' || myChar == '\r')
{
state = out;
}
else if (state == out) /* We enter a new word */
{
state = in;
wordNumber++;
}
}
printf("\n%d word(s)\n", wordNumber);
}
int main (int argc, char *argv[])
{
FILE* myFile = NULL;
myFile = fopen(argv[1], "r");
if (myFile != NULL) /* Testing if fopen worked */
{
wordCount (myFile);
fclose(myFile);
}
else if (argc == 1) /* Is the file path supplied ? */
{
printf ("No file supplied as an argument.");
}
else
{
printf("There was a problem accessing the file. Please make sure the file exists and is available.");
}
return 0;
}
It doesn't use
bool, instead uses
enum, which have many advantages (the most important of which being improving source code readability). I kow that
enum was added to the original C later on. I wonder if it follows the C89 norm.
Instead of enums,
defines could be used.
Also, in this code, file is supplied as a command line argument, allowing you not to change the source code (and recompile), every time you need to change files.
I hope the code is clear enough. Do not hesitate to give any remarks and criticism, I'm listening :)