gpt4 book ai didi

c++ - 为什么 ifstream 文件中的换行符 - 当被这段代码读取时 - 占用 2 个字节?

转载 作者:搜寻专家 更新时间:2023-10-31 01:31:54 27 4
gpt4 key购买 nike

我使用的文件有 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 编码的文件。

This answer提供更多详细信息。

关于c++ - 为什么 ifstream 文件中的换行符 - 当被这段代码读取时 - 占用 2 个字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44645395/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com