为什么 ifstream 文件中的换行符(当通过此代码读取时)占用 2 个字节?

2024-01-14

我使用的文件有 15 行,每行 2 个字符,因此假设文件的大小约为 44 字节,但使用tellg 函数,大小显示为 58。此外,我累积了一个包含所有位置的数组代码正在识别一个换行符,它们都是连续的,因此证实了这个疑问。谢谢你!

//Tailfile - This program accepts a file and prints the last 10 lines.
//This function determines the number of lines and how to display it
int lineidentifier(fstream&tailfile,long& position)
{
    tailfile.seekg(0,ios::end);//sets the read position at the end of file.
    long n=0;//counter for the number of lines
    long i=tailfile.tellg();//counter for the number of characters set to 
                        //thenumber of bytes in the file and hence, the end.
    char ch;//To hold and check the character.
    while(n<10&&i>=0)//conditions are as long as the number of characters 
                 //are not exhausted or the number of lines
    {
        tailfile.seekg(i, ios::beg);//sets the read position to the end of 
                   //the file by using the number of characters and the file
                                //mode as the beginning.
        cout<<"1. "<<i<<endl;//DEBUGGING EXTRA
        tailfile.get(ch);//Reads the content at i
        tailfile.clear();//clears the eof flag set by the first iteration 
                          //because we reach the end of the file.
        cout<<"2. "<<i<<endl;//DEBUGGING EXTRA
        if(ch=='\n')//if the character received is the newline character 
                 //leading to us regarding it as a line has been identified.
        {
            n++;//Increment n accordingly.
            position=i;//The position is the byte i is at before the 
                 //character was read, hence the position of the character.
            cout<<position<<endl;//DEBUGGING EXTRA
            cout<<ch<<endl;//DEBUGGING EXTRA
            i--;
        }
        i--;
        cout<<"4. "<<i<<endl;//DEBUGGING EXTRA
    }
    cout<<i<<endl;//DEBUGGING EXTRA
    if(i<=1)//Using the position of i to indicate whether the file has more 
         //than 10 lines. If i is less than 1, it has reached the
    //beginning of the file
        return 0;
    else
        return 1;
}

Linux用途\n(换行,0x0A)作为新行字符。

Windows/DOS 使用\r\n(回车符(0x0D)和换行符(0x0A))作为其新行字符。

您可能正在读取 DOS 编码的文件。

这个答案 https://stackoverflow.com/questions/1552749/difference-between-cr-lf-lf-and-cr-line-break-types提供了更多详细信息。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么 ifstream 文件中的换行符(当通过此代码读取时)占用 2 个字节? 的相关文章

随机推荐