C ++ FStream抛出异常错误

时间:2016-02-18 10:19:09

标签: c++ fstream

我正在使用WinSock从互联网上下载我的文件。

此代码演示了我从标题中获取内容大小,而不是删除标题并将其余内容写入应用程序。 FileDownload1.write(...)它会引发Access违规读取错误。

这段代码有什么问题吗? (我习惯使用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]);
}

如果你需要它,请告诉我,(但是完整的源代码有点混乱,因为我只是试图扼杀这个以找出如何下载文件并将其成功写入计算机。

2 个答案:

答案 0 :(得分:1)

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

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

请参阅:fstream::write

答案 1 :(得分:0)

您正在访问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());