繁体   English   中英

C ++ FStream抛出异常错误

[英]C++ FStream throwing exception error

我正在使用WinSock从Internet下载我的文件。

这里的代码演示了我从标头获取内容的大小,而不是删除标头并将其余的内容写入应用程序。 FileDownload1.write(...)它将引发访问冲突读取错误。

这段代码有什么问题吗? (我习惯于使用C风格的字符串,所以我还不是100%熟悉C ++标准字符串。

这是我的一些代码:

    DWORD WINAPI DownloadFile(LPVOID VoidAtt){

    ...

    postion = TextBuffer.find("Content-Length: ", 0);
    std::string LengthOfFile = TextBuffer.substr(postion + strlen("Content-Length: "), 7);
    int FileSize = std::stoi(LengthOfFile, nullptr, 10);
    postion = TextBuffer.find("\r\n\r\n", 0);
    std::string memoryblock = TextBuffer.substr(postion + 4, -1);
    std::ofstream FileDownload1;

    FileDownload1.open("64bit1.m4a", std::ios::out | std::ios::binary);
    FileDownload1.write(memoryblock.c_str(), FileSize);
    FileDownload1.close();

    SetWindowTextA(hTextBox, &TextBuffer[0]);
}

如果您需要全部,请让我知道,(但是完整的源代码有点混乱,因为我只是想尝试一下此方法,以弄清楚如何下载文件并将其成功写入计算机。

第二个写参数必须是内存大小:

 FileDownload1.write(memoryblock.c_str(), memoryblock.size());

请参阅: fstream :: write

您正在访问其memoryblock

假设您的TextBuffer的内容是这样的:

Content-Length:      10\r\n\r\nSomeText

然后让我们遍历您的代码:

postion = TextBuffer.find("Content-Length: ", 0);
//position = 0
std::string LengthOfFile = TextBuffer.substr(postion + strlen("Content-Length: "), 7);
//LengthOfFile = "     10"
int FileSize = std::stoi(LengthOfFile, nullptr, 10);
// FileSize = 10
postion = TextBuffer.find("\r\n\r\n", 0);
//position = 23
std::string memoryblock = TextBuffer.substr(postion + 4, -1);
//memoryblock = "SomeText"

memoryblock的数据大小为8(如果计算\\0则为9),而FileSize为10。

当然,此示例是使用无效数据创建的。 但是,您应该检查数据从何处开始,而不仅仅是信任Content-Length 我不太确定,但是如果Content-Length也计算\\r\\n\\r\\n那么您将始终跳过4。

您应该添加大小检查,最后使用它来确保您处于范围内:

FileDownload1.write(memoryblock.c_str(), memoryblock.size());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM