如何检查文件中的最后一行是否包含“\n”(或换行符)。
这里有两个例子: a file with newline at the end - a file without newline at the end
我当前的代码:
fstream file("filename");
string line;
if (!file.is_open()) throw Exception();
while(getline(file, line))
{
(checking for lastline)
}
我意识到 getline 不会包含 new_line 字符。我可以遍历每个角色,但会有一个性能问题。有些文件有数百万个字符,我不知道如何转到末尾行来获取 new_line 字符。
--- 编辑 ---
- 也许我忘了提及我的环境仅是 UNIX。所以我会 仅使用行尾字符 '\n'。
- 其次,我需要 getline 来检查每一行是否有错误(但与此处无关)。
- 我会在 while 循环之前检查我的最后一行,这样如果文件无效,我就可以喝它!
- 我的图像显示 CR LF,这是我的错。为这个错误感到抱歉。应该只有LF。
最佳答案
您可以使用seekg跳转到文件中的任意位置。
file.seekg(-1,ios_base::end); // go to one position before the EOF
char c;
file.get(c); // Read current character
if(c=='\n'){
cout<<"yes"<<endl; // You have new_line character
}
因此我们跳转到 EOF 之前的一个位置并读取最后一个字符。如果是新行,则完成。
关于c++ - 如何检查文件最后一行的 new_line 字符? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36820881/