繁体   English   中英

在C ++中实现“tail -f”

[英]Implement “tail -f” in C++

我想在C ++中创建一个与“tail-f”功能相同的小代码:在文本文件中查看新行并在标准输出中显示它们。

想法是有一个监视文件的线程

有没有一种简单的方法可以在不打开和关闭文件的情况下每次都这样做?

继续阅读文件。 如果读取失败,则不执行任何操作。 没有必要反复打开和关闭它。 但是,如果您的操作系统提供文件,您会发现使用特定于操作系统的功能来监视文件会更有效。

看一下Linux上的inotify或Mac OS上的kqueue。

Inotify是Linux内核子系统,允许您订阅文件上的事件,当文件发生时,它会报告给您的应用程序。

https://stackoverflow.com/a/7514051/44729相同,但下面的代码使用getline而不是getc并且不跳过新行

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>

using namespace std;

static int last_position=0;
// read file untill new line
// save position

int find_new_text(ifstream &infile) {

   infile.seekg(0,ios::end);
   int filesize = infile.tellg();

   // check if the new file started
   if(filesize < last_position){
      last_position=0;
   }  
   // read file from last position  untill new line is found 

   for(int n=last_position;n<filesize;n++) {

      infile.seekg( last_position,ios::beg);
      char  test[256]; 
      infile.getline(test, 256);
      last_position = infile.tellg();
      cout << "Char: "  << test <<"Last position " << last_position<<  endl;
      // end of file 
      if(filesize == last_position){
        return filesize;
      } 

  }

  return 0;
}


int main() {

  for(;;) {
    std::ifstream infile("filename");
    int current_position = find_new_text(infile);
    sleep(1);
  } 

} 

我在Perl手册中读到了这个,但它很容易翻译成标准C,而C又可以转换成istream

   seek FILEHANDLE,POSITION,WHENCE
      Sets FILEHANDLE's position, just like the "fseek" call of
      "stdio".  
       <...>
       A WHENCE of 1 ("SEEK_CUR") is useful for not moving the file 
       position:

           seek(TEST,0,1);

       This is also useful for applications emulating "tail -f".  Once
       you hit EOF on your read, and then sleep for a while, you might
       have to stick in a seek() to reset things.  The "seek" doesn't
       change the current position, but it does clear the end-of-file
       condition on the handle, so that the next "<FILE>" makes Perl
       try again to read something.  We hope.

据我所知, fseek被称为iostream::seekg 所以你基本上应该这样做:寻找到文件的末尾,然后睡觉并再次使用ios_base::cur标志来更新文件结尾并读取更多数据。

取而代之的sleep ING,你可以使用的inotify,如建议对方的回答 ,(而从模拟文件读取,实际上是块)睡觉准确,直到该文件被更新/关闭。 但这是特定于Linux的,而不是标准的C ++。

我也需要实现它,我只是在标准C ++中编写了一个快速入侵。 黑客在文件中搜索最后一个0x0A(换行符),并在最后一个换行值变为较大值时输出该换行后的所有数据。 代码在这里:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;


int find_last_linefeed(ifstream &infile) {

  infile.seekg(0,ios::end);
  int filesize = infile.tellg();

  for(int n=1;n<filesize;n++) {
    infile.seekg(filesize-n-1,ios::beg);

    char c;
    infile.get(c);

    if(c == 0x0A) return infile.tellg();
  }
}


int main() {


  int last_position=-1;
  for(;;) {

    ifstream infile("testfile");
    int position = find_last_linefeed(infile);

    if(position > last_position) {
      infile.seekg(position,ios::beg);
      string in;
      infile >> in;
      cout << in << endl;
    }
    last_position=position;

    sleep(1);
  }

}
#include <iostream>
#include <fstream>
#include <string>
#include <list>
#include <sys/stat.h> 
#include <stdlib.h>

#define debug 0

class MyTail
{
private:
std::list<std::string> mLastNLine;
const int mNoOfLines;
std::ifstream mIn;

public:

explicit MyTail(int pNoOfLines):mNoOfLines(pNoOfLines) {}

const int getNoOfLines() {return mNoOfLines; }

void getLastNLines();

void printLastNLines();

void tailF(const char* filename);

};

void MyTail::getLastNLines() 
{
    if (debug) std::cout << "In: getLastNLines()" << std::endl;
    mIn.seekg(-1,std::ios::end);
    int pos=mIn.tellg();
    int count = 1;

    //Get file pointer to point to bottom up mNoOfLines.
    for(int i=0;i<pos;i++)
    {
        if (mIn.get() == '\n')
            if (count++ > mNoOfLines)
                break;
        mIn.seekg(-2,std::ios::cur);
    }

    //Start copying bottom mNoOfLines string into list to avoid I/O calls to print lines
    std::string line;
    while(getline(mIn,line)) {
        int data_Size = mLastNLine.size();
        if(data_Size >= mNoOfLines) {
            mLastNLine.pop_front();
        }
        mLastNLine.push_back(line);
    }

    if (debug) std::cout << "Out: getLastNLines()" << std::endl;
}

void MyTail::printLastNLines()
{    
     for (std::list<std::string>::iterator i = mLastNLine.begin();  i !=         mLastNLine.end(); ++i)
     std::cout << *i << std::endl;
}

void MyTail::tailF(const char* filename)
{
    if (debug) std::cout << "In: TailF()" << std::endl;

    int date = 0;
    while (true) {
        struct stat st;
        stat (filename, &st);
        int newdate = st.st_mtime;
        if (newdate != date){
            system("@cls||clear");
            std::cout << "Print last " << getNoOfLines() << " Lines: \n";
            mIn.open(filename);
            date = newdate;
            getLastNLines();
            mIn.close();
            printLastNLines();
        }
    }
    if (debug) std::cout << "Out: TailF()" << std::endl;        
}

int main(int argc, char **argv)
{
    if(argc==1) {
        std::cout << "No Extra Command Line Argument Passed Other Than Program Name\n"; 
        return 0;
    }

    if(argc>=2) {
        MyTail t1(10);
        t1.tailF(argv[1]);
    }
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM