简体   繁体   English

监视文件中的更改

[英]monitoring a file for changes

I'm trying to achieve tail -like functionality in my Visual Studio 2008 C++ application. 我正在尝试在Visual Studio 2008 C ++应用程序中实现类似尾部的功能。 (ie show in real-time the changes to a file not owned by my process.) (即实时显示对我的进程不拥有的文件的更改。)

/// 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;
    }
}

While it always knows how many bytes have been added to the file, the read buffer is always empty. 尽管它始终知道已向文件添加了多少字节,但读取缓冲区始终为空。 What do I need to do to get the functionality I'm after? 我需要做什么才能获得所需的功能?

Thanks, PaulH 谢谢PaulH


EDIT: nevermind. 编辑:没关系。 I got it sorted. 我把它整理好了。 I was using seekg() incorrectly. 我使用了不正确的seekg()。 This is what I should have been doing: 这是我应该做的:

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

Thanks 谢谢

On Linux you could look at inotify to be notified of changes to a file. 在Linux上,您可以查看inotify来通知文件更改。 It allows you to poll or select an inotify descriptor and get notified when a file or directory has changed. 它允许您轮询或选择inotify描述符,并在文件或目录更改时得到通知。

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

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