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 );
unsigned char
and the allocation should bebuffer = new unsigned char[length + 1]
and thenbuffer[length] = '\0'
. I know that the question was posted many years ago, but nobody has written about this.ios::binary
, adding a zero-terminator as you suggested makes no sense. Also difference between using achar
orunsigned char
does not make much difference here, as the code is not trying to interpret the file content. What is wrong with the above code is thesizeof(buffer)
is 4 or 8 (32/64-bit pointer). So it always writes 4/8 bytes into the output file. Author should uselength
instead ofsizeof(buffer)
.sizeof(buffer)
is the size of a pointer to characters. That will be the same whether you have allocated the memory or not. In this case, the variablelength
has the quantity you need to pass tofread
so just use that.