【发布时间】:2009-12-08 13:43:59
【问题描述】:
要求:
我必须读到 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
【问题讨论】:
-
文件不是两个进程之间通信的最佳工具。您应该考虑使用套接字。
-
我知道,如果我使用套接字,我的困惑会少得多,但这是针对我们必须使用文件的项目。