要求 :
我必须从特定文件读取直到 EOF(一次 16 个字节),然后说睡眠 5 秒。现在,在 5 秒后,当我尝试从文件中读取(其内容到那时将被附加)时,预期的设计必须以这样一种方式从它之前离开的点读取并再次扫描内容(每次 16 个字节)直到到达 EOF。
我已经使用 ifstream 编写了(基本)代码以从给定文件中读取(直到 EOF - 一次 16 个字节),如下所示:
#include <stdio.h>
#include <fstream>
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
int fd, i, j, length, pos;
char buffer[100][16];
ifstream Read;
std::ostringstream oss;
int current_position = 0;
Read.open("from4to5", ios::binary);
//Get the size of the file
Read.seekg(0, ios::end);
length = Read.tellg();
Read.seekg(0, ios::beg);
for(i=0; i<length; i++)
{
buffer[i][16] = '\0';
}
//Read the file in 16byte segments or eof(), whichever comes first
//Testing the return condition of the function is preferred, as opposed to testing eof()
while(Read.get(buffer[i], 17))
{
for(j=0; j<=16; j++)
oss << buffer[i][j];
cout << "Contents : " << oss.str() << endl;
oss.seekp(0);
i++;
}
// Output is :
// Contents : BD8d3700indiaC#E
// Contents : BD6d4700godgeD3E
// Contents : BD9d1311badge3TE
return 0;
}
我需要修改它以满足我的要求。我尝试使用 seekg() 调用,但不知何故失败了。我想知道,当我第一次访问文件并将其读取到文件流时,程序是否会以某种方式在文件上放置一个排他锁,这意味着我下次将无法读取它.
谁能告诉我怎么做?
文件名:“from4to5” 内容:
BD8d3700indiaC#EBD6d4700godgeD3EBD9d1311badge3TE
在 5 秒内,其他一些进程写入(追加)到同一个文件“from4to5” 现在,
文件内容:
BD8d3700indiaC#EBD6d4700godgeD3EBD9d1311badge3TEBD6d1210clerk41EBD2d1100mayor47EBD4d2810bread6YE
现在,当程序从“from4to5”文件中读取时,它必须从之前离开的位置开始读取,每次读取 16 个字节,直到遇到 EOF。
这次的输出意图是:
// Output is :
// Contents : BD6d1210clerk41E
// Contents : BD2d1100mayor47E
// Contents : BD4d2810bread6YE