1

要求 :


我必须从特定文件读取直到 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
4

2 回答 2

4

您必须:
保存您的位置
关闭文件
重新打开文件
寻找您保存的位置并继续阅读直到 EOF

于 2009-12-08T14:09:43.790 回答
2

您应该能够清除输入流上的 EOF 标志并继续阅读。

while (true)
{
    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++;
    }
    Read.clear();
    sleep(5);
}

如果您在写入文件的同时读取,您可能会遇到问题,您无法读取所有 16 个字节。这可能会导致一些间歇性的、难以追踪的错误。至少,您应该添加一些错误检查。

于 2009-12-08T14:20:14.507 回答