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

Basilisk picture Basilisk · Nov 14, 2013 · Viewed 12.9k times · Source

I have searched for it everywhere, but I can not seem to understand how to use ios::cur. I need to read a whole file in chunks of 10 bytes, write those bytes into a buffer and then write that buffer into another file. For that I send the first 10 bytes, then the next 10 and so on. But how do i make sure the pointer starts from the last iteration's position?

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 '\0'
            is.read(data, sz);

            data[sz] = '\0'; // set '\0' 
            cout << " data size: " << strlen(data) << "\n";
            cout << data;
            i = i + 10;
        }
        obj.close();
    }
}

Answer

Thomas Matthews picture Thomas Matthews · Nov 14, 2013

You should not need to reposition the file positions.

The file positions get updated after every read operation.

You should use two file objects, one for input another for output.

In both cases, the file positions are updated after each read and write operation.

Edit 1: Simplified example

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

If the input_file is position at offset 0, then after the first read, the file position will be at 16. This can be verified by:

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);
}