手动实现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
";
    return ;
  }
  int len = 0;
  // while(fin.get(tmp)) {
  //   if (tmp == '
')
  //     len++;
  //  //单个字符读取
  // }
  while(getline(fin, tmp)) {
    // if (tmp == '
')
      len++;
    // cout << "aaa == " << tmp << '
';
  }
  fin.clear();
  fin.seekg(0, ios::beg);
  if (num <= len) {
    while(getline(fin, tmp)) {
      if (num == len)
        cout << tmp << '
';
      else
        num++;
    }
  } 
  else {
    while(getline(fin, tmp)) {
      cout << tmp << "
";
    }
  }
}

int main()
{
  tail("2.txt", 1);
  return 0;
}
原文地址:https://www.cnblogs.com/lalalatianlalu/p/11232506.html