binary file to CString

C

Carl Forsman

given the following base64_encode function, I will read bytes from a
file and encode the binary data into a single line CString;

but something wrong with the following code with errors!

================
std::string base64_encode(unsigned char const* bytes_to_encode,
unsigned int in_len) {

================
#define BYTE unsigned char
....
int size;
BYTE* buffer;
....
std::ifstream inputFile("C:\\test.bin", std::ios::in |
std::ios::binary);

// open the binary file to read
if (inputFile.is_open())
{

inputFile.seekg(0, std::ios::end);
size = inputFile.tellg(); // size of the file

buffer = new BYTE[size];
inputFile.read(buffer, size);

// encode binary data into a Base64 string
std::string data = base64_encode(buffer, size);
// convert std::string to CString
CString st = CString(data);

}
 
M

Michael DOUBEZ

Carl Forsman a écrit :
given the following base64_encode function, I will read bytes from a
file and encode the binary data into a single line CString;

but something wrong with the following code with errors! [snip]
inputFile.seekg(0, std::ios::end);
size = inputFile.tellg(); // size of the file

buffer = new BYTE[size];
inputFile.read(buffer, size);

Your file cursor is at the end of the file. Add the following before
reading:
inputFile.seekg(0,ios::beg);
 
S

Stefan Ram

Carl Forsman said:
inputFile.seekg(0, std::ios::end);

In ISO/IEC 9899:1990:

»A binary stream need not meaningfully support
fseek calls with a whence value of SEEK_END.«

Footnote 225 even mentions »undefined behavior«:

»225) Setting the file position indicator to end-of-file,
as with fseek(file, 0, SEEK_END), has undefined behavior
for a binary stream (because of possible trailing null
characters) or for any stream with state-dependent
encoding that does not assuredly end in the initial shift
state.«

In ISO/IEC 14882:2003(E), »seekg« and »tellg« seem to be
defined using »pubseekoff«, which seems to be based on
»seekoff«, which seems to be based on »::std::fseek«,
for which the above quotation from ISO/IEC 9899:1990 applies.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top