如果您擅长一次又一次地打开和关闭文件,则此问题的正确解决方案是存储最后读取的位置,并在文件更新后从那里开始:
确切的算法将是:
- 设置 start_pos = 0 ,结束 pos =0
- 更新 end_pos = infile.tellg(),
- 将 get 指针移动到 start_pos(使用 seekg())并读取块(end_pos - start_pos)。
- 更新 start_pos = end_pos 然后关闭文件。
- 睡眠一段时间,然后再次打开文件。
- 如果文件流仍然不好,请关闭文件并跳转到步骤 5。
- 如果文件流良好,则跳至步骤 1。
所有 c++ 参考都在http://www.cplusplus.com/reference/istream/istream/seekg/
你可以使用这里给出的示例代码。
确切的代码将是:
`
#include <iostream>
#include <fstream>
int main(int argc, char *argv[]) {
if (argc != 2)
{
std::cout << "Please pass filename with full path \n";
return -1;
}
int end_pos = 0, start_pos = 0;
long length;
char* buffer;
char *filePath = argv[1];
std::ifstream is(filePath, std::ifstream::binary);
while (1)
{
if (is) {
is.seekg(0, is.end);
end_pos = is.tellg(); //always update end pointer to end of the file
is.seekg(start_pos, is.beg); // move read pointer to the new start position
// allocate memory:
length = end_pos - start_pos;
buffer = new char[length];
// read data as a block: (end_pos - start_pos) blocks form read pointer
is.read(buffer, length);
is.close();
// print content:
std::cout.write(buffer, length);
delete[] buffer;
start_pos = end_pos; // update start pointer
}
//wait and restart with new data
sleep(1);
is.open(filePath, std::ifstream::binary);
}
return 0;
}
`