Implement “tail -f” in C++

后端 未结 6 600
灰色年华
灰色年华 2020-12-10 03:47

I want to create a small code in C++ with the same functionality as \"tail-f\": watch for new lines in a text file and show them in the standard output.

The idea is

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-10 03:53

    I needed to implement this too, I just wrote a quick hack in standard C++. The hack searches for the last 0x0A (linefeed character) in a file and outputs all data following that linefeed when the last linefeed value becomes a larger value. The code is here:

    #include 
    #include 
    #include 
    
    using namespace std;
    
    
    int find_last_linefeed(ifstream &infile) {
    
      infile.seekg(0,ios::end);
      int filesize = infile.tellg();
    
      for(int n=1;n last_position) {
          infile.seekg(position,ios::beg);
          string in;
          infile >> in;
          cout << in << endl;
        }
        last_position=position;
    
        sleep(1);
      }
    
    }
    

提交回复
热议问题