一、代碼
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
int main()
{
std::ifstream fin("E:/test.txt", std::ios::ate);
if (!fin)
return -1;
int state = 0;
// 先倒回文件末尾兩個字符
fin.seekg(-2, fin.cur);
int lineCount = 200;
for (int i = 0; i < lineCount; i++)
{
// 查看前一個字符是否爲回車符
while (fin.peek() != fin.widen('\n'))
{
fin.seekg(-1, fin.cur);
if (fin.tellg() == -1)
{
state = 1;
break;
}
}
fin.seekg(-1, fin.cur);
}
if (state == 1)
{
fin.clear();
fin.seekg(0);
}else{
fin.seekg(2, fin.cur);
}
std::string line;
while (getline(fin, line))
{
cout << line << endl;
}
fin.clear();
fin.close();
return 0;
}
二、原理
倒着一個一個字符的判斷 當識別到’\n’後就相當於 一行。