从文件中读取和写入字节(c ++)

时间:2010-02-18 02:28:41

标签: c++ file-io

我想我可能不得不使用fstream对象,但我不确定如何。基本上我想将文件读入字节缓冲区,修改它,然后将这些字节重写为文件。所以我只需要知道如何进行字节i / o。

4 个答案:

答案 0 :(得分:7)

#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();

从记忆中我认为这就是它的方式。

答案 1 :(得分:1)

如果您处理的是小文件,我建议您阅读整个文件会更容易。然后使用缓冲区并再次写出整个块。它们向您展示了如何读取块 - 假设您从上面的回复中填写打开的输入/输出文件

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

答案 2 :(得分:0)

在执行文件I / O时,您必须在循环中读取文件,检查文件结尾和错误情况。您可以使用上面的代码

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

答案 3 :(得分:0)

#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();
}
相关问题