监视文件以进行更改

时间:2010-09-10 19:37:27

标签: c++ filestream

我正在尝试在Visual Studio 2008 C ++应用程序中实现类似tail的功能。 (即实时显示不属于我的进程的文件的更改。)

/// name of the file to tail
std::string file_name_;

/// position of the last-known end of the file
std::ios::streampos file_end_;

// start by getting the position of the end of the file.
std::ifstream file( file_name_.c_str() );
if( file.is_open() )
{
    file.seekg( 0, std::ios::end );
    file_end_ = file.tellg();
}

/// callback activated when the file has changed
void Tail::OnChanged()
{
    // re-open the file
    std::ifstream file( file_name_.c_str() );
    if( file.is_open() )
    {
        // locate the current end of the file
        file.seekg( 0, std::ios::end );
        std::streampos new_end = file.tellg();

        // if the file has been added to
        if( new_end > file_end_ )
        {
            // move to the beginning of the additions
            file.seekg( 0, new_end - file_end_ );

            // read the additions to a character buffer
            size_t added = new_end - file_end_;
            std::vector< char > buffer( added + 1 );
            file.read( &buffer.front(), added );

            // display the additions to the user

            // this is always the correct number of bytes added to the file
            std::cout << "added " << added << " bytes:" << std::endl;

            // this always prints nothing
            std::cout << &buffer.front() << std::endl << std::endl;
        }

        // remember the new end of the file
        file_end_ = new_end;
    }
}

虽然它总是知道已经向文件添加了多少字节,但读缓冲区始终为空。 我需要做些什么才能获得我追求的功能?

谢谢, PaulH


编辑:没关系。我把它分类了。我错误地使用了seekg()。这就是我应该做的事情:

if( new_end > file_end_ )
{
    size_t added = new_end - file_end_;
    file.seekg( -added, std::ios::end );

由于

1 个答案:

答案 0 :(得分:1)

在Linux上,您可以查看inotify以获得有关文件更改的通知。它允许您轮询或选择inotify描述符,并在文件或目录发生更改时收到通知。