在每个文件的末尾是否总是有一个新的行字符( ) ?

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

本文关键字:有一个 字符 文件 是否      更新时间:2023-10-16
#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;
}

文件"input.txt":

ab
c

理论上,正好有四个字符'a', 'b', 'n', 'c'(我自己打的)

但实际上,上述程序的输出是:'a', 'b', 'n', 'c', 'n'。

有人能帮我吗?

我假设您在linux中编辑input.txt,大多数linux编辑器在最后一行末尾附加LF字符。

Windows使用CRLF (rn, 0D 0A)行结尾,而Linux/Unix只使用LF (n, 0A)。

如果您不希望发生这种情况,在windows上编辑文件并将文件复制到linux并执行相同的操作,而不更改任何代码。我用两种方法执行代码,得到以下输出

在Linux上编辑input.txt时。97 98 10 99 10

input.txt在Windows上编辑并复制到Linux时。97 98 13 10 99

不,不能保证文件以n或任何字符结束,甚至是ASCII EOF字符(这对我来说没有意义)。文件只是一个任意字节流。你可以有零字节的文件,1字节的文件,2字节的文件,等等,而不确定这些字节是什么。

文件通常以n结尾,因为它们是在这样的循环中编写的:

for(int i=0;i<numberOfLines;i++) {
    fs << getSomeText( i ) << endl;
}
fs.close();

注意endl,它将导致每行,包括最后一行,以n结尾。

当然,在Windows上是rn,而老派的Mac操作系统是r,只是为了尴尬。

相关文章: