|
-
July 12th, 2010, 02:06 PM
#1
Read File Into Buffer And Write That Buffer To Another File?
Hey everyone, I'm trying to play around with a few things. Now I'm playing around with reading binary files (and now I'm playing with writing). Now heres something weird, I'm reading a file into a buffer, but that buffer wrote write properly to another file.
Code:
unsigned char *Buffer, *Buffer2;
DWORD FileSize, BytesRead;
HANDLE hFile = CreateFile ( "app.exe", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
SelectedFileSize = GetFileSize ( hFile, NULL );
if ( hFile == NULL )
{
MessageBox ( NULL, "Invalid filename...exiting!", "Error", NULL );
//return 0;
}
if ( ( FileSize = GetFileSize ( hFile, NULL ) ) < 0 )
{
MessageBox ( NULL, "Error Retrieving File Size", "Error", NULL );
CloseHandle ( hFile );
exit ( 0 );
}
Buffer2 = Buffer = ( unsigned char* ) malloc ( FileSize );
if ( !ReadFile ( hFile, Buffer, FileSize, &BytesRead, NULL ) )
{
MessageBox ( NULL, "Error Reading File", "Error", NULL );
CloseHandle ( hFile );
free ( Buffer );
exit ( 0 );
}
As you can see in the above code, I'm just reading it into the buffer.
Now, when I try something along the lines of:
Code:
HANDLE MyFile = CreateFile ( "filename.ext", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0, NULL );
DWORD Bytes;
WriteFile(MyFile, (unsigned char*)Buffer, sizeof ( Buffer ), &Bytes, NULL);
CloseHandle(MyFile);
or:
Code:
FILE * pFile = fopen("filename.ext", "r+b");
fwrite(Buffer, sizeof ( Buffer ), sizeof ( Buffer ), pFile);
fclose(pFile);
The only thing it writes is "MZ ÿÿ ". Which isn't even close to the full size of the file (the file is about 3.5 KB total).
I know I'm doing something wrong, but I can't figure what. Would you all mind giving me a hand?
-
July 12th, 2010, 03:21 PM
#2
Re: Read File Into Buffer And Write That Buffer To Another File?
WriteFile(MyFile, (unsigned char*)Buffer, sizeof ( Buffer ), &Bytes, NULL);
Buffer is a pointer. Size of pointer is 4, but not what you expected. You have to use BytesRead instead.
Best regards,
Igor
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|