读写二进制文件 [英] Reading and writing binary file
本文介绍了读写二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想写code读取二进制文件到一个缓冲区,然后写缓冲区到另一个文件。我有以下的code,但缓冲区只存储一对夫妇的ASCII字符从文件和任何其他在第一线。
INT长;
字符*缓冲区;ifstream的是;
is.open(C:\\\\ Final.gif,IOS ::二进制);
//获取文件的长度:
is.seekg(0,内部监督办公室::月底);
长度= is.tellg();
is.seekg(0,内部监督办公室::求);
//分配内存:
缓冲区=新的char [长度]
//读取数据块:
is.read(缓冲液,长度);
is.close();FILE * PFILE;
PFILE = FOPEN(C:\\\\ myfile.gif,W);
FWRITE(缓冲,1,sizeof的(缓冲),PFILE);
解决方案
如果你想这样做C ++的方式,像这样做:
的#include<&的fstream GT;
#包括LT&;&迭代器GT;
#包括LT&;&算法GT;诠释的main()
{
性病:: ifstream的输入(C:\\\\ Final.gif的std :: IOS ::二进制);
的std :: ofstream的输出(C:\\\\ myfile.gif的std :: IOS ::二进制); 性病::复制(
的std :: istreambuf_iterator<焦炭>(输入)
的std :: istreambuf_iterator<焦炭>()
的std :: ostreambuf_iterator<焦炭>(输出));
}
如果您需要在缓冲区中的数据进行修改,或什么的,做到这一点:
的#include<&的fstream GT;
#包括LT&;&迭代器GT;
#包括LT&;矢量>诠释的main()
{
性病:: ifstream的输入(C:\\\\ Final.gif的std :: IOS ::二进制);
//拷贝所有的数据到buffer
的std ::矢量<&烧焦GT;缓冲((
的std :: istreambuf_iterator<焦炭>(输入))
(性病:: istreambuf_iterator<焦炭>()));
}
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.
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:
#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<char> buffer((
std::istreambuf_iterator<char>(input)),
(std::istreambuf_iterator<char>()));
}
这篇关于读写二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文