[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.c++

binary file to CString

Carl Forsman

11/19/2008 7:58:00 AM

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);

}
2 Answers

Michael DOUBEZ

11/19/2008 8:59:00 AM

0

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);
--
Michael

ram

11/19/2008 11:24:00 AM

0

Carl Forsman <fatwallet951@yahoo.com> writes:
>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.