读取和写入二进制文件

问题描述:

我想写代码读取二进制文件到缓冲区,然后将缓冲区写入另一个文件。我有以下代码,但缓冲区仅存储文件第一行中的几个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); 
+18

您应该决定使用iostream还是C文件处理。请不要同时使用两者。 – frast 2011-03-24 14:03:39

如果你想做到这一点的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)); 
} 

如果你需要数据对其进行修改或东西的缓冲区,这样做:

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

int main() 
{ 
    std::ifstream input("C:\\Final.gif", std::ios::binary); 
    // copies all data into buffer 
    std::vector<char> buffer((
      std::istreambuf_iterator<char>(input)), 
      (std::istreambuf_iterator<char>())); 
} 
+0

我想知道这些效率如何? – Mikhail 2013-10-10 09:36:17

+1

如果我只想复制一部分数据缓冲区,该怎么办?我如何做到这一点?比方说1024字节。 – likern 2014-07-10 15:45:25

+5

@Mikhail [Here](http://insanecoding.blogspot.it/2011/11/how-to-read-in-file-in-c.html)你可以找到一些基准。 – 2016-02-01 16:06:47

sizeof(buffer)是最后一行上指针的大小而不是缓冲区的实际大小。 您需要使用您已经建立的“长度”而不是

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

sizeof(buffer) == sizeof(char*) 

改为使用长度。

此外,最好使用fopen与“wb” ......

+0

不能使用缓冲区的'buffer.length()'可能会在其中有NULL值,从而影响strlen/length()的目的。 – 2017-08-30 17:06:08

+0

最好使用'sizeof(buffer)'。 – 2017-08-30 18:50:34

下面是一个简单的例子,使用rdbuf C++的方式。我从网上得到了这个。我找不到我的这个原始出处:

#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; 
} 
+6

最好的,非便携式的方法是让操作系统复制你的文件。毕竟,这是它为谋生所做的一部分。无需*重新发明轮子*。 – 2011-03-24 17:08:48

+7

?没有命名空间?这是什么,九十年代? – BarbaraKwarc 2017-01-13 10:31:09

+0

@BarbaraKwarc:根据您的要求更新。 – 2017-01-13 18:16:22

我严重不理解为什么会有人选择写时,它可以在下面的代码段这样一个简单的命令,发生这样的复杂的代码。

复制任何大小的整个文件。没有尺寸限制!

只要使用它。测试和工作!

#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; 
} 

具有较小的缓冲区大小将是复制小文件有帮助。即使是“char buffer [2]” 也可以完成这项工作。

+6

如果文件大小不是缓冲区大小的倍数?此外,为什么你必须声明你的缓冲区为'int []'而不是'char []'? – firegurafiku 2016-05-13 11:33:32