简体   繁体   中英

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

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.

#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.

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
  ..........

While doing file I/O, you will have to read the file in a loop checking for end of file and error conditions. You can use the above code like this

while (fileBufferHere.good()) {  
    filebufferHere.getline(m_content, 1024)  
    /* Do your work */  
}
#include <iostream>
#include <fstream>

const static int BUF_SIZE = 4096;

using std::ios_base;

int main(int argc, char** argv) {

   std::ifstream in(argv[1],
      ios_base::in | ios_base::binary);  // Use binary mode so we can
   std::ofstream out(argv[2],            // handle all kinds of file
      ios_base::out | ios_base::binary); // content.

   // Make sure the streams opened okay...

   char buf[BUF_SIZE];

   do {
      in.read(&buf[0], BUF_SIZE);      // Read at most n bytes into
      out.write(&buf[0], in.gcount()); // buf, then write the buf to
   } while (in.gcount() > 0);          // the output.

   // Check streams for problems...

   in.close();
   out.close();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM