简体   繁体   English

读写二进制文件

[英]Reading and writing binary file

I'm trying to write code to read a binary file into a buffer, then write the buffer to another file.我正在尝试编写代码将二进制文件读入缓冲区,然后将缓冲区写入另一个文件。 I have the following code, but the buffer only stores a couple of ASCII characters from the first line in the file and nothing else.我有以下代码,但缓冲区只存储文件第一行中的几个 ASCII 字符,没有其他任何内容。

int length;
char * buffer;

ifstream is;
is.open ("C:\\Final.gif", ios::binary );
// get length of file:
is.seekg (0, ios::end);
length = is.tellg();
is.seekg (0, ios::beg);
// allocate memory:
buffer = new char [length];
// read data as a block:
is.read (buffer,length);
is.close();

FILE *pFile;
pFile = fopen ("C:\\myfile.gif", "w");
fwrite (buffer , 1 , sizeof(buffer) , pFile );

If you want to do this the C++ way, do it like this:如果您想以 C++ 方式执行此操作,请执行以下操作:

#include <fstream>
#include <iterator>
#include <algorithm>

int main()
{
    std::ifstream input( "C:\\Final.gif", std::ios::binary );
    std::ofstream output( "C:\\myfile.gif", std::ios::binary );

    std::copy( 
        std::istreambuf_iterator<char>(input), 
        std::istreambuf_iterator<char>( ),
        std::ostreambuf_iterator<char>(output));
}

If you need that data in a buffer to modify it or something, do this:如果您需要缓冲区中的数据来修改它或其他东西,请执行以下操作:

#include <fstream>
#include <iterator>
#include <vector>

int main()
{
    std::ifstream input( "C:\\Final.gif", std::ios::binary );

    // copies all data into buffer
    std::vector<unsigned char> buffer(std::istreambuf_iterator<char>(input), {});

}

Here is a short example, the C++ way using rdbuf .这是一个简短的示例,使用rdbuf的 C++ 方式。 I got this from the web.这是我从网上得到的。 I can't find my original source on this:我找不到我的原始来源:

#include <fstream>
#include <iostream>

int main () 
{
  std::ifstream f1 ("C:\\me.txt",std::fstream::binary);

  std::ofstream f2 ("C:\\me2.doc",std::fstream::trunc|std::fstream::binary);

  f2<<f1.rdbuf();

  return 0;
}
 sizeof(buffer) == sizeof(char*) 

Use length instead.改用长度。

Also, better to use fopen with " wb "....另外,最好将fopen与“ wb ”一起使用....

sizeof(buffer) is the size of a pointer on your last line NOT the actual size of the buffer. sizeof(buffer) 是最后一行指针的大小,而不是缓冲区的实际大小。 You need to use "length" that you already established instead您需要使用您已经建立的“长度”

您应该将长度传递给 fwrite 而不是 sizeof(buffer)。

Here is implementation of standard C++ 14 using vectors and tuples to Read and Write Text,Binary and Hex files .这是使用向量元组读取和写入Text,Binary and Hex files的标准 C++ 14 的实现。

Snippet code :片段代码:

try {
if (file_type == BINARY_FILE) {

    /*Open the stream in binary mode.*/
    std::ifstream bin_file(file_name, std::ios::binary);

    if (bin_file.good()) {
        /*Read Binary data using streambuffer iterators.*/
        std::vector<uint8_t> v_buf((std::istreambuf_iterator<char>(bin_file)), (std::istreambuf_iterator<char>()));
        vec_buf = v_buf;
        bin_file.close();
    }

    else {
        throw std::exception();
    }

}

else if (file_type == ASCII_FILE) {

    /*Open the stream in default mode.*/
    std::ifstream ascii_file(file_name);
    string ascii_data;

    if (ascii_file.good()) {
        /*Read ASCII data using getline*/
        while (getline(ascii_file, ascii_data))
            str_buf += ascii_data + "\n";

        ascii_file.close();
    }
    else {
        throw std::exception();
    }
}

else if (file_type == HEX_FILE) {

    /*Open the stream in default mode.*/
    std::ifstream hex_file(file_name);

    if (hex_file.good()) {
        /*Read Hex data using streambuffer iterators.*/
        std::vector<char> h_buf((std::istreambuf_iterator<char>(hex_file)), (std::istreambuf_iterator<char>()));
        string hex_str_buf(h_buf.begin(), h_buf.end());
        hex_buf = hex_str_buf;

        hex_file.close();
    }
    else {
        throw std::exception();
    }
}

} }

Full Source code can be found here完整的源代码可以在这里找到

It can be done with simple commands in the following snippet.可以使用以下代码段中的简单命令来完成。

Copies the whole file of any size.复制任意大小的整个文件。 No size constraint!没有大小限制!

Just use this.就用这个。 Tested And Working!!测试和工作!

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
  ifstream infile;
  infile.open("source.pdf",ios::binary|ios::in);

  ofstream outfile;
  outfile.open("temppdf.pdf",ios::binary|ios::out);

  int buffer[2];
  while(infile.read((char *)&buffer,sizeof(buffer)))
  {
      outfile.write((char *)&buffer,sizeof(buffer));
  }

  infile.close();
  outfile.close();
  return 0;
}

Having a smaller buffer size would be helpful in copying tiny files.具有较小的缓冲区大小将有助于复制小文件。 Even "char buffer[2]" would do the job.甚至“char buffer[2]”也能完成这项工作。

There is a much simpler way.有一个更简单的方法。 This does not care if it is binary or text file.这并不关心它是二进制文件还是文本文件。

Use noskipws.使用 noskipws。

char buf[SZ];
ifstream f("file");
int i;
for(i=0; f >> noskipws >> buffer[i]; i++);
ofstream f2("writeto");
for(int j=0; j < i; j++) f2 << noskipws << buffer[j];

Or you can just use string instead of the buffer.或者您可以只使用字符串而不是缓冲区。

string s; char c;
ifstream f("image.jpg");
while(f >> noskipws >> c) s += c;
ofstream f2("copy.jpg");
f2 << s;

normally stream skips white space characters like space or new line, tab and all other control characters.通常流会跳过空白字符,如空格或换行符、制表符和所有其他控制字符。 But noskipws makes all the characters transferred.但是 noskipws 使所有字符都转移了。 So this will not only copy a text file but also a binary file.所以这不仅会复制文本文件,还会复制二进制文件。 And stream uses buffer internally, I assume the speed won't be slow.并且流在内部使用缓冲区,我认为速度不会很慢。

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

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