开发者

(C++) read an arbirtrary file as binary and output the data as a separate text file

开发者 https://www.devze.com 2023-04-01 04:47 出处:网络
I\'m trying to take an arbitrary file and read it as raw binary and then output the data as a separate text file. No assumptions whatsoever can made about the input file as to formatting or encoding.

I'm trying to take an arbitrary file and read it as raw binary and then output the data as a separate text file. No assumptions whatsoever can made about the input file as to formatting or encoding. What I've done is (very) roughly:

char *pDataBlock = new char[nLength];
 ifstream InputFile("MyInputFile.txt", ios::in | ios::binary);
 ofstream OutputFile("MyOutputFile.txt"); 
 while (InputFile)
 { 
  InputFile.read(pDataBlock, nLength);
  OutputFile.write(pDataBlock, nLength);
 }  

CURRENT PROBLEM: This code opens MyInputFile.txt in binary mode, but reads one character (byte!) at a time into a C-string called pDataBlock. This C-string is then written to MyOutputFile.开发者_如何学编程txt one byte at a time.

BAD SOLUTION: The solution that I have now is to insert the following steps to the above code: (1) read a single character of the InputFile, (2) cast this character into an integer, (3) convert the integer to a binary string, (4) output this binary string to OutputFile in append mode, (5) read the next character until EOF.

The problem seems to be that every read/write command I've found associated with fstream involves taking one byte at a time and doesn't allow for bit level manipulations.


You're right, streams cannot operator at lower granularity than one byte. The solution you have right now is not that bad. You can improve it by reading more than one byte at a time, but there's no way to read one bit at a time from a file stream.

0

精彩评论

暂无评论...
验证码 换一张
取 消