我正在尝试使用Win32从URL将图像下载到用户的桌面上。我已经处理了所有HTTP请求内容,并且知道它运行良好。当我去打电话CreateFile()
给Visual Studios调试器时,只说“异常:Application.exe触发了一个断点”,它将在CreateFile()行中恢复。也有一个错误代码“检测到严重错误c0000374”
这是我的代码:
VARIANT varResponse;
VariantInit(&varResponse);
...
hr = pIWinHttpRequest->get_ResponseBody(&varResponse);
...
if (SUCCEEDED(hr)) {
long upperBounds;
long lowerBounds;
unsigned char* buff;
//Make sure that varResponse is an array of unsigned bytes
if (varResponse.vt == (VT_ARRAY | VT_UI1)) {
long Dims = SafeArrayGetDim(varResponse.parray);
//It should only have one dimension
if (Dims == 1) {
//Get Array lower and upper bounds
SafeArrayGetLBound(varResponse.parray, 1, &lowerBounds);
SafeArrayGetUBound(varResponse.parray, 1, &upperBounds);
upperBounds++;
SafeArrayAccessData(varResponse.parray, (void**)&buff);
HANDLE hFile;
DWORD dwBytesWritten;
PWSTR filepath[MAX_PATH];
HRESULT hr = SHGetKnownFolderPath(FOLDERID_Desktop, 0, NULL, &*filepath);
if (SUCCEEDED(hr)) {
//PathCombine(filepathForImage, filepathToDesktop, L"\\todaysDailyImage.jpg");
PathAppend(*filepath, L"todaysDailyImage.jpg");
MessageBox(NULL, *filepath, L"Check if filepath works", MB_OK);
}
hFile = CreateFile(*filepath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
//File failed
}
else {
WriteFile(hFile, buff, upperBounds - lowerBounds, &dwBytesWritten, NULL);
//File was written
}
CloseHandle(hFile);
CoTaskMemFree(filepath);
SafeArrayUnaccessData(varResponse.parray);
MessageBox(NULL, L"Everything was cleaned up", L"Update:", MB_OK);
}
}
}
我做错什么了吗?
您使用的方式filepath
是完全错误的。
您将其声明为MAX_PATH
(260)个PWSTR
指针数组。
当仅通过数组名称来引用数组时,最终会得到一个指向数组第1个元素的指针。因此,&*filepath
与&*(&filepath[0])
有效相同&filepath[0]
。和*filepath
一样*(&filepath[0])
,这是有效的filepath[0]
。因此,就SHGetKnownFolderPath()
和MessageBox()
而言,它们仅PWSTR
在数组中的第1个指针上操作,而其他259个数组元素将被忽略。那部分还可以,但是很浪费。
但是,PathAppend()
需要一个目标缓冲区,该目标缓冲区是元素MAX_PATH
数量的数组WCHAR
。您将追加到分配为其输出的WCHAR[]
数组,该数组的SHGetKnownFolderPath()
大小不足以容纳您尝试追加到其的文件名。因此,您触发错误是因为您试图修改尚未分配来保存该修改的内存。
您根本不需要PWSTR
数组。尝试类似这样的方法:
PWSTR folderpath;
HRESULT hr = SHGetKnownFolderPath(FOLDERID_Desktop, 0, NULL, &folderpath);
if (FAILED(hr)) {
// ...
}
else {
PWSTR filepath;
hr = PathAllocCombine(folderpath, L"todaysDailyImage.jpg", 0, &filepath);
if (FAIlED(hr)) {
// ...
}
else {
MessageBoxW(NULL, filepath, L"Check if filepath works", MB_OK);
hFile = CreateFileW(filepath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
//File failed
}
else {
WriteFile(hFile, buff, upperBounds - lowerBounds, &dwBytesWritten, NULL);
//File was written
CloseHandle(hFile);
}
LocalFree(filepath);
}
CoTaskMemFree(folderpath);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句