Linux – get one more number of bytes reported in a file

fileslinux

Why do I get one byte more reported? I do not have a newline at the end. I tested other files with similar result. Using linux 3.2.

$ cat testfile.txt 
aabbcd

$ wc -c testfile.txt 
7 testfile.txt

Similarly I get one more number of bytes reported if I use c++:

...
file(filename, std::ifstream::in | std::ios::binary);
file.seekg(0, std::ifstream::end);
int fsize = file.tellg();
...

The text aabbcd consist of 6 characters, in ASCII encoding that should be 6 bytes.
Why do I get 7 bytes reported?

Note: I happend to have characters in the example, but I care only about the bytes, not text, not formatted input.

Best Answer

vi and many other editors add an extra line feed to the end of the file even if you don't add one manually. For example, writing aabbcd in vi, not pressing return and saving gives a file that od -x dumps as;

0000000      6161    6262    6463    000a
0000007

...which is (a little endian dump of) aabbcd + line feed.

ls -l will also show the file as 7 bytes;

$ ls -l testfile.txt 
-rw-r--r--  1 me  staff  7 Jul 26 09:52 testfile.txt

Most likely, this is the case with your file too.

Related Question