CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Nov 2005
    Posts
    281

    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 &#255;&#255; ". 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?

  2. #2
    Join Date
    Nov 2000
    Location
    Voronezh, Russia
    Posts
    6,633

    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
  •  





Click Here to Expand Forum to Full Width

Featured