请问读写二进制文件

读写二进制文件

我正在尝试编写代码将二进制文件读入缓冲区,然后将缓冲区写入另一个文件。我有以下代码,但缓冲区只存储文件中第一行的几个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 );



拉莫斯之舞
浏览 332回答 3
3回答

胡说叔叔

如果你想用C ++方式做这个,那就这样做:#include&nbsp;<fstream>#include&nbsp;<iterator>#include&nbsp;<algorithm>int&nbsp;main(){ &nbsp;&nbsp;&nbsp;&nbsp;std::ifstream&nbsp;input(&nbsp;"C:\\Final.gif",&nbsp;std::ios::binary&nbsp;); &nbsp;&nbsp;&nbsp;&nbsp;std::ofstream&nbsp;output(&nbsp;"C:\\myfile.gif",&nbsp;std::ios::binary&nbsp;); &nbsp;&nbsp;&nbsp;&nbsp;std::copy(&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;std::istreambuf_iterator<char>(input),&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;std::istreambuf_iterator<char>(&nbsp;), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;std::ostreambuf_iterator<char>(output));}如果您需要缓冲区中的数据来修改它或其他内容,请执行以下操作:#include&nbsp;<fstream>#include&nbsp;<iterator>#include&nbsp;<vector>int&nbsp;main(){ &nbsp;&nbsp;&nbsp;&nbsp;std::ifstream&nbsp;input(&nbsp;"C:\\Final.gif",&nbsp;std::ios::binary&nbsp;); &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;copies&nbsp;all&nbsp;data&nbsp;into&nbsp;buffer &nbsp;&nbsp;&nbsp;&nbsp;std::vector<unsigned&nbsp;char>&nbsp;buffer(std::istreambuf_iterator<char>(input),&nbsp;{});}

三国纷争

这是一个简短的例子,使用C ++方式rdbuf。我从网上得到了这个。我找不到我原来的来源:#include&nbsp;<fstream>#include&nbsp;<iostream>int&nbsp;main&nbsp;()&nbsp;{ &nbsp;&nbsp;std::ifstream&nbsp;f1&nbsp;("C:\\me.txt",std::fstream::binary); &nbsp;&nbsp;std::ofstream&nbsp;f2&nbsp;("C:\\me2.doc",std::fstream::trunc|std::fstream::binary); &nbsp;&nbsp;f2<<f1.rdbuf(); &nbsp;&nbsp;return&nbsp;0;}

呼唤远方

&nbsp;sizeof(buffer)&nbsp;==&nbsp;sizeof(char*)请改用长度。另外,最好使用fopen“&nbsp;wb”....
打开App,查看更多内容
随时随地看视频慕课网APP