Reading and writing bytes from a file (C ++)

I think I will probably have to use the fstream object, but I'm not sure how to do this. Essentially, I want to read the file into a byte buffer, modify it, and then overwrite these bytes in the file. So I just need to know how to do I / O bytes.

+5
source share
3 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 it is.

+7
source

If you are dealing with a small file size, I recommend that reading the entire file is easier. Then work with the buffer and write the entire block again. They show you how to read the block - provided that you fill in the open I / O file from the answer above.

  // 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
  ..........
+1
source

/ , .

while (fileBufferHere.good()) {  
    filebufferHere.getline(m_content, 1024)  
    /* Do your work */  
}
0
source

All Articles