Hello,
I am trying to open a file, read the file,display the characters on the screen and process the data for stats.
I am able to open the file, read the file and then it is either display it or just process the data.
if i remove this part ,
/* Read one line of text */
fgets( c, 100, pFile );
/* Print it to stdout */
printf( "%s", c );
line 32 and 34, i am able to process the data.
Please note - I am able to read from a text file that is in the same folder as my source code. I called the file "text.txt" and i just type some thing inside it. Make sure the letter q is included. q acts like the end of file.I have tried EOF but does not work. I don't know why. let me know if you know why.
Where is the bug?
Thanks for your help
Code:
/* SS7q3 - Programming Exercise 11-11 modified */
#include <stdio.h>
#include <ctype.h> // for character testing
#include <stdbool.h> // for boolean
#define STOP 'q'
int main(void)
{
char c[100]; // read in character
char filename[100];
int ch;
int n_words = 0; // number of words
int n_upper = 0; // number of uppercase characters
int n_lower = 0; // number of lowercase characters
int n_punc = 0; // number of punctuation marks
int n_digit = 0; // number of digits
FILE * pFile;
bool inword = false; // == true if c is in a word
printf("Enter the filename to be analyzed\n");
gets(filename);
pFile = fopen(filename, "r" );
if (!pFile)
fprintf( stderr, "I couldn't open the file.\n" );
/* Programs gets stuck with the code below*/
else
{
/* Read one line of text */
fgets( c, 100, pFile );
/* Print it to stdout */
printf( "%s", c );
while ((ch = getc(pFile)) != STOP)
{
if (!isalpha(ch) && !inword)
{
inword = true; // starting a new word
n_words++; // count word
}
if (isalpha(ch) && inword)
inword = false; // reached end of word
if (isupper(ch))
n_upper++;
else if (islower(ch))
n_lower++;
else if (ispunct(ch))
n_punc++;
else if (isdigit(ch))
n_digit++;
}
}
printf("\nwords = %d, uppercase = %d, lowercase = %d, "
"punctuation = %d, digits = %d\n",
n_words,n_upper,n_lower, n_punc, n_digit);
fclose(pFile);
/* Pause program to view result */
printf("\nPress [Enter] to exit, Bye.\n\n");
fflush(stdin);
getchar();
return 0;
}