Kuljeet
Kuljeet

Reputation: 19

getchar() function to count characters in C

I have a code that counts the number of characters. It uses getchar() and while execution I use (./a.out < test.txt) where test.txt is locally saved text file. Issue is that the counter is showing a value greater than the characters in the file.

When I use the condition,

while((c = getchar()) != EOF && c != '\n')

instead of

while((c = getchar()) != EOF)

in the function where c is an int defined in main, the counter is correct.

int main() 
{
    long nc=0; int c;
    while((c = getchar()) != EOF)
    {
        putchar(c);
        ++nc;
    }
    printf("%ld", nc);
}

I think that the issue is due to '\n' character. When I use putchar(c) as shown above, let's say that there are 9 characters in my test.txt file. Now, it should print all the characters in the file followed by 9 as output. But, it prints 10 instead. Also, the command prompt shifts to next line after displaying characters which is the reason behind printing 10 as it counts '\n' as a character. But, from where did that '\n' came from?

Upvotes: 1

Views: 1281

Answers (1)

David Collins
David Collins

Reputation: 3012

I would wager that you haven't actually verified the size of your file. Double check the size with either

ls -ls test.txt

or

wc -c test.txt

Open your file in a hex editor. I suspect you will find a new-line character (0x0A) at the end.

But, from where did that '\n' came from?

That depends on how you created or edited the file in the first place.

If you created using

echo "Test file" > test.txt

for example, then bash will automatically add a new-line character at the end. Certain text editors may do the same.

Upvotes: 1

Related Questions