简体   繁体   中英

Is there always a new line character (\n) in the end of every file?

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ifstream inStream("input.txt");
    char next;
    inStream.get(next);
    while(! inStream.eof( ))
    {
        cout << (int) next << " ";
        inStream.get(next);
    }
    return 0;
}

file "input.txt":

ab
c

In theory, there are exactly four character 'a', 'b', '\\n', 'c' ( I typed them by myself )

But in fact, the output of the above-mentioned program is : 'a', 'b', '\\n', 'c', '\\n'.

Could anyone please help me?

I assume You are editing input.txt in linux and most linux editors appaend LF character at end of last line.

Windows uses CRLF (\\r\\n, 0D 0A) line endings while Linux/Unix just uses LF (\\n, 0A).

If you do not want this to happen , edit file on windows and copy file to linux and execute same without changing any code. I executed code with both ways and got below output.

When input.txt is edited on Linux. 97 98 10 99 10

When input.txt is edited on Windows and copied to Linux. 97 98 13 10 99

Hope this helps.

No, there is no guarantee a file ends in \\n - or any character, even the ASCII EOF character (which makes no sense to me). A file is just a stream of arbitrary bytes. You can have zero-byte files, 1-byte, 2-byte, and so on with nothing certain about what those bytes are.

Often files DO end in \\n because they're written in a loop like this:

for(int i=0;i<numberOfLines;i++) {

    fs << getSomeText( i ) << endl;
}
fs.close();

Note the endl , which will cause every line, including the last line, to end with \\n .

Of course, on Windows it's \\r\\n and old-school (pre-OS X) Mac OS it's \\r , just to be awkward.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM