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*/

Recommended Answers

All 2 Replies

>Its urgent
For future reference, stating that your problem is urgent will likely be counterproductive. A lot of us are perverse enough to ignore you solely because you're in a rush.

Anyway, the immediate problem is your word counting logic isn't a part of the loop. That's not a very effective state machine. ;) Compare and contrast:

while ((cur = fgetc(fp1)) != EOF)
{
    if (cur != '\n')
        ++countCh;
    else
        ++countLn;

    if (Space)
        word = 'O';
    else
    {
        if (word == 'O')
        {
            ++countWd;
            word = 'I';
        }
    }
}

>Its urgent
For future reference, stating that your problem is urgent will likely be counterproductive. A lot of us are perverse enough to ignore you solely because you're in a rush.

Sad but true...

commented: Worthless "me too" post. Please refrain. -2
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.