3

I created a file like this

a v
bb
e

And I didn't press enter after typing e in the last line.

So there are four characters in the first line 'a',' ','v','\n'.

There are three characters in the second line 'b','b','\n'.

And there is one character in the last line 'e'.

So there are totally 8 characters in this file. But when I count the characters using the following C program:

#include<stdio.h>

/* count characters in input; 1st version */
int main()
{
    long nc;

    nc = 0;
    while (getchar() != EOF) {
        ++nc;
    }
    printf("%ld\n", nc);

    return 0;
}

It gave me 9. Even when I use wc command to count, it is still 9. Why?

moooeeeep
  • 31,622
  • 22
  • 98
  • 187
Rivers Shall
  • 531
  • 1
  • 3
  • 13
  • 2
    Something added the extra newline. You can verify with a command such as `od -c` (or `ls -l`, of course!). What command did you use to create the file? Most editors will add the final newline automatically. You can do it with plain `cat` but you'd have to type control-D twice after the 'e'. – Jonathan Leffler May 29 '18 at 07:14
  • *"I created a file like this"* -- **how** did you create the file? Some editors automatically put a newline at the end of the last line of the file (if it is not already there). – axiac May 29 '18 at 07:21
  • What editor are you using? vi/vim adds a newline for you. – Keith Thompson May 29 '18 at 07:35
  • Your editor is properly adding a POSIX *end-of-file*. Some editors provide an option for end of line clean-up, others are just oblivious to the specification. – David C. Rankin May 29 '18 at 07:36

1 Answers1

2

There's reasoning in favor of having all lines terminated with a newline character:

And there are text editors that are set up to add a trailing newline character automatically (if not already there):

Probably that is why you observe the unexpected file size.

To inspect the actual content of such files, I like to use hexdump:

$ hexdump -C test
00000000  61 20 76 0a 62 62 0a 65  0a                       |a v.bb.e.|
00000009
moooeeeep
  • 31,622
  • 22
  • 98
  • 187