Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read and write bytes from a file (c++)

Tags:

c++

file-io

I think I probably have to use an fstream object but i'm not sure how. Essentially I want to read in a file into a byte buffer, modify it, then rewrite these bytes to a file. So I just need to know how to do byte i/o.

like image 699
jmasterx Avatar asked Feb 18 '10 02:02

jmasterx


2 Answers

#include <fstream>

ifstream fileBuffer("input file path", ios::in|ios::binary);
ofstream outputBuffer("output file path", ios::out|ios::binary);
char input[1024];
char output[1024];

if (fileBuffer.is_open())
{
    fileBuffer.seekg(0, ios::beg);
    fileBuffer.getline(input, 1024);
}

// Modify output here.

outputBuffer.write(output, sizeof(output));

outputBuffer.close();
fileBuffer.close();

From memory I think this is how it goes.

like image 144
Craig Avatar answered Sep 17 '22 07:09

Craig


If you are dealing with a small file size, I recommend that reading the whole file is easier. Then work with the buffer and write the whole block out again. These show you how to read the block - assuming you fill in the open input/output file from above reply

  // open the file stream
  .....
  // use seek to find the length, the you can create a buffer of that size
  input.seekg (0, ios::end);   
  int length = input.tellg();  
  input.seekg (0, ios::beg);
  buffer = new char [length];
  input.read (buffer,length);

  // do something with the buffer here
  ............
  // write it back out, assuming you now have allocated a new buffer
  output.write(newBuffer, sizeof(newBuffer));
  delete buffer;
  delete newBuffer;
  // close the file
  ..........
like image 40
Fadrian Sudaman Avatar answered Sep 19 '22 07:09

Fadrian Sudaman