在 C++ 中以字节块为单位读取和写入文件

read and write file in chunks of bytes in c++

本文关键字:读取 文件 为单位 C++ 字节      更新时间:2023-10-16

我已经到处搜索过它,但我似乎无法理解如何使用ios::cur。我需要以 10 个字节的块读取整个文件,将这些字节写入缓冲区,然后将该缓冲区写入另一个文件。为此,我发送前 10 个字节,然后发送接下来的 10 个字节,依此类推。但是如何确保指针从上次迭代的位置开始呢?

char* data = 0;
int i = 0;
std::ifstream is("test.txt", std::ifstream::binary);
if (is)
{
    is.seekg(0, is.end);
    int size = is.tellg();
    cout << size << endl;
    ofstream obj;
    obj.open("new.txt");
    while (!is.eof())
    {
        for (; i <= size;)
        {
            is.seekg(i, is.beg);
            int sz = is.tellg();
            // cout<<sz<<endl;
            data = new char[sz + 1]; //  for the ''
            is.read(data, sz);
            data[sz] = ''; // set '' 
            cout << " data size: " << strlen(data) << "n";
            cout << data;
            i = i + 10;
        }
        obj.close();
    }
}

您不需要重新定位文件位置。

文件位置在每次读取操作后都会更新。

应使用两个文件对象,一个用于输入,另一个用于输出。

在这两种情况下,文件位置都会在每次读取和写入操作后更新。

编辑 1:简化示例

#define BUFFER_SIZE 16
unsigned char buffer[BUFFER_SIZE];
//...
while (input_file.read((char *)buffer, BUFFER_SIZE))
{
  output_file.write((char *)buffer, BUFFER_SIZE);
}

如果input_file的位置为偏移量 0,则在第一次读取后,文件位置将为 16。 这可以通过以下方式验证:

int read_file_position = input_file.tellg();  
cout << "input file position: " << read_file_position << endl;
while (input_file.read((char *)buffer, BUFFER_SIZE))
{
  read_file_position = input_file.tellg();
  cout << "input file position: " << read_file_position << endl;
  output_file.write((char *)buffer, BUFFER_SIZE);
}

我认为可以简化为:

char* data = 0;
int i = 0;
int size = 0;
int sz = 10;
std::ifstream is("test.txt", std::ifstream::binary);
std::ofstream obj;
data = new char[sz+1];
int read_sz = 0;
if (is)
{
    obj.open("new.txt");
    read_sz = is.tellg(); //we are at the beginning of the file now
    while (!is.eof())
    {
        int old_read_sz = read_sz; // old position - before next read
        is.read(data, sz);
        read_sz = is.tellg(); // new position, we've read read_sz-old_read_sz bytes
        data[read_sz-old_read_sz] = ''; // set ''
        // I hope you wanted the two lines below only for debugging purposes :)
        cout << " data size so far: " << read_sz << "n";
        cout << data << endl;
        obj.write(data, read_sz-old_read_sz);
     }
    obj.close();
    is.close();
    cout << "total data size: "<< read_sz << endl;
}

读取数据块后,文件光标已经移过该块,因此您无需自己重新定位它(并且从当前位置移动到末尾/开始和返回可能会很昂贵 - 时间上 - 特别是如果你有一个大的输入文件)。

顺便说一下,这里有一个关于该主题的教程:http://www.cplusplus.com/doc/tutorial/files/

更新:忘记了是.read() != 旧的 C 样式读取 :-}