// Method I`m using to read words,Characters,whitespaces,new lines from a file.. // But when i run it only the upper while gets executed and if i place the below whileloop first, //only that gets executed. In short only one while loop gets executed. // How can i address it??
#include<stdlib.h>
#include<string.h>
int count_items(FILE *f);
// MAIN CODE
int main()
{
printf("-------Programm to count_items in a file-------\n");
FILE *f = fopen("sample.txt","r");
count_items(f);
fclose(f);
return 0;
}
//FUNCTION TO COUNT NUMBER OF ITEMS IN A FILE
int count_items(FILE *f)
{
int word_count,line_count,white_count,char_count;
char sbuff[100],cbuff;
// **Method I`m using to read characters from a file..**
while((cbuff=getc(f))!=EOF)
{
char_count++;
if(cbuff=='\n')
{
line_count++;
}
if(cbuff==' ')
{
white_count++;
}
}
while(fscanf(f,"%s",sbuff)==1)
{
word_count++;
}
// PRINT THE RESULT
printf("The number of words in file are %d\n\n",word_count );
printf("The number of characters in file are %d\n\n",char_count );
printf("The number of whitespaces in file are %d\n\n",white_count );
printf("The number of lines in file are %d\n\n",line_count );
return 0;
} ```
// **IT SEEMS THAT I NEED TO FLUSH THE BUFFER BEFORE GOING TO SECOND WHILE LOOP. IF SO , HOW DO I DO THAT?**