繁体   English   中英

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

[英]Read and write bytes from a file (c++)

我想我可能不得不使用一个fstream对象,但我不知道如何。 基本上我想将文件读入字节缓冲区,修改它,然后将这些字节重写为文件。 所以我只需要知道如何进行字节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();

从记忆中我认为这是怎么回事。

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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