1
我試圖在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);
感謝
你可以看看** tail **是如何實現的: http://stackoverflow.com/questions/1439799/how-can-i-get-the-source-code-for-the- linux-utility-tail/1439832#1439832 – karlphillip 2010-09-10 19:40:39
它看起來並不像你已經null終止緩衝區... – 2010-09-10 19:54:57
@Billy ONeal - 我想我做到了。向量大小中的+1應爲NULL終結符騰出空間。 – PaulH 2010-09-10 19:59:40