如何从IStream读取到char数组并将其写入另一个IStream?

时间:2012-12-05 01:43:17

标签: c++ windows visual-studio sockets istream

我正在尝试通过套接字连接发送图像,但我遇到以下代码的问题:

//stream to char array
STATSTG myStreamStats;
ULONG bytesSaved;
myStream->Stat(&myStreamStats, 0);
char* streamData = new char[myStreamStats.cbSize.QuadPart];
if(myStream->Read(streamData, myStreamStats.cbSize.QuadPart, &bytesSaved) == S_OK)
    cout<<"OK!"<<endl;
else
    cout<<"Not OK!"<<endl;

//char array to stream
if(myStreamR->Write(streamData, myStreamStats.cbSize.QuadPart, &bytesSaved) == S_OK)
    cout<<"OK!"<<endl;
else
    cout<<"Not OK!"<<endl;

//saving the image to a file
myImage = Image::FromStream(myStreamR);
myImage->Save(lpszFilename, &imageCLSID, NULL);

程序编译并运行,但我没有得到我的图像。如果我使用原始的“myStream”而不是“myStreamR”,我会得到它,它是从原始流中读取的char数组构造的。

输出是两个“OK!”,这意味着所有字节都被复制到数组中,并且所有字节都被粘贴到新流中。但是,我检查了savedBytes,我发现在read()之后它的值是0(不好),而在write()之后,它等于我给出的流大小。那么为什么在地球上读取()如果没有读取任何内容会给我一个“S_OK”标志?

1 个答案:

答案 0 :(得分:6)

在向数据写入数据后,您并不是在寻找MyStreamRImage::FromStream()开始读取流的当前位置,所以如果你不回头,那么就没有数据可供阅读。

试试这个:

STATSTG myStreamStats = {0};
if (FAILED(myStream->Stat(&myStreamStats, 0)))
    cout << "Stat failed!" << endl;
else
{
    char* streamData = new char[myStreamStats.cbSize.QuadPart];

    ULONG bytesSaved = 0;
    if (FAILED(myStream->Read(streamData, myStreamStats.cbSize.QuadPart, &bytesSaved)))
        cout << "Read failed!" << endl;
    else
    {
        //char array to stream
        if (FAILED(myStreamR->Write(streamData, bytesSaved, &bytesSaved)))
            cout << "Write failed!" << endl;
        else
        {
            LARGE_INTEGER li;
            li.QuadPart = 0;

            if (FAILED(myStreamR->Seek(li, STREAM_SEEK_SET, NULL)))
                cout << "Seek failed!" << endl;
            else
            {
                //saving the image to a file
                myImage = Image::FromStream(myStreamR);
                if (myImage1->GetLastStatus() != Ok)
                    cout << "FromStream failed!" << endl;
                else
                {
                    if (myImage->Save(lpszFilename, &imageCLSID, NULL) != Ok)
                        cout << "Save failed!" << endl;
                    else
                        cout << "OK!" << endl;
                }
            }
        }
    }
}