5

I have an IStream which I know it contains a PNG file, but I can't write its content into a file like normal I/O stream, I don't know if I am doing something wrong or I should do a different thing for writing IStream into file.

    IStream *imageStream;
    std::wstring imageName;
    packager.ReadPackage(imageStream, &imageName);      

    std::ofstream test("mypic.png");
    test<< imageStream;
Am1rr3zA
  • 7,115
  • 18
  • 83
  • 125
  • You need to use the binary writing methods for image data. `<<` will corrupt the file in certain systems. Try `std::ofstream test("mypic.png", std::ios::binary); test.write(...);` I don't know how IStream() works to fill in the blanks. – Galik Sep 20 '14 at 00:41

1 Answers1

5

Based on the IStream reference you gave here is some untested code that should do roughly what you want:

void output_image(IStream* imageStream, const std::string& file_name)
{
    std::ofstream ofs(file_name, std::ios::binary); // binary mode!!

    char buffer[1024]; // temporary transfer buffer

    ULONG pcbRead; // number of bytes actually read

    // keep going as long as read was successful and we have data to write
    while(imageStream->Read(buffer, sizeof(buffer), &pcbRead) == S_OK && pcbRead > 0)
    {
        ofs.write(buffer, pcbRead);
    }

    ofs.close();
}
Galik
  • 47,303
  • 4
  • 80
  • 117