【问题标题】:monitoring a file for changes监视文件的更改
【发布时间】:2010-09-10 19:37:27
【问题描述】:

我正在尝试在我的 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;
    }
}

虽然它总是知道文件中添加了多少字节,但读取缓冲区始终是空的。 我需要做什么才能获得我想要的功能?

谢谢, 保罗H


编辑:没关系。我整理好了我错误地使用了 seekg()。这是我应该做的:

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

谢谢

【问题讨论】:

  • 你可以看看 tail 是如何实现的:stackoverflow.com/questions/1439799/…
  • 看起来你没有终止缓冲区...
  • @Billy ONeal - 我想我做到了。向量大小中的 +1 应该为 NULL 终止符腾出空间。
  • @karlphillip - 感谢您的链接。我将查看该代码。

标签: c++ filestream


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多