I have to count characters, words and lines from a text file.
I am able to count characters and lines but not words.
This code is error-less, but the output for words always appear 0.
Anyone able to help me see what's wrong and provide a way out?
And I need one more requirement.
I am only able to use system calls such as open, read, write, close instead of the usual fopen, fwrite, fclose. Could you help me see how it could be changed too?
Its urgent, Thank you so much.
(:
/* This program counts characters words and lines in a text file */
#include <stdio.h>
#define Space (cur == ' ' || cur == '\n' || cur == '\t')
int main (void)
{ /*local definitions*/
int cur;
int preCh;
int countLn = 0;
int countCh = 0;
int countWd = 0;
char word = 'O'; /* When word contains the letter I, we are in a word; when it
contains the letter O, we are out of a word*/
FILE *fp1;
/*Statements*/
if (!(fp1 = fopen("textFile.txt", "r")))
{
printf("Error in opening textFile.txt for reading");
return (1);
} /* if open error*/
while ((cur = fgetc(fp1)) != EOF)
{
if (cur != '\n')
countCh++;
else
countLn++;
preCh= cur;
} /* while */
if (preCh != '\n')
countLn++;
if (Space)
word = 'O';
else
if (word == 'O')
{
countWd++;
word = 'I';
} /*else*/
printf("\n");
printf("Number of characters: %d\n", countCh);
printf("Number of lines: %d\n", countLn);
printf("Number of words: %d\n", countWd);
printf("\n");
fclose(fp1);
return 0;
} /*main*/