[英]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]);
}
如果您需要全部,請讓我知道,(但是完整的源代碼有點混亂,因為我只是想嘗試一下此方法,以弄清楚如何下載文件並將其成功寫入計算機。
您正在訪問其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.