手动实现tail
中间会把文件指针重新置到文件开始,要配合clear一起使用
#include <bits/stdc++.h> using namespace std; void tail(string path, int num) { ifstream fin(path); string tmp; if (!fin) { cout << "the file is not open\n"; return ; } int len = 0; // while(fin.get(tmp)) { // if (tmp == '\n') // len++; // //单个字符读取 // } while(getline(fin, tmp)) { // if (tmp == '\n') len++; // cout << "aaa == " << tmp << '\n'; } fin.clear(); fin.seekg(0, ios::beg); if (num <= len) { while(getline(fin, tmp)) { if (num == len) cout << tmp << '\n'; else num++; } } else { while(getline(fin, tmp)) { cout << tmp << "\n"; } } } int main() { tail("2.txt", 1); return 0; }