Windows file system is case insensitive. How, given a file/folder name (e.g. "somefile"), I get the actual name of that file/folder (e.g. it should return "SomeFile" if Explorer displays it so)?
Some ways I know, all of which seem quite backwards:
Given the full path, search for each folder on the path (via FindFirstFile). This gives proper cased results of each folder. At the last step, search for the file itself.
Get filename from handle (as in MSDN example). This requires opening a file, creating file mapping, getting it's name, parsing device names etc. Pretty convoluted. And it does not work for folders or zero-size files.
Am I missing some obvious WinAPI call? The simplest ones, like GetActualPathName() or GetFullPathName() return the name using casing that was passed in (e.g. returns "program files" if that was passed in, even if it should be "Program Files").
I'm looking for a native solution (not .NET one).
And hereby I answer my own question, based on original answer from cspirz.
Here's a function that given absolute, relative or network path, will return the path with upper/lower case as it would be displayed on Windows. If some component of the path does not exist, it will return the passed in path from that point.
It is quite involved because it tries to handle network paths and other edge cases. It operates on wide character strings and uses std::wstring. Yes, in theory Unicode TCHAR could be not the same as wchar_t; that is an exercise for the reader :)
std::wstring GetActualPathName( const wchar_t* path )
{
// This is quite involved, but the meat is SHGetFileInfo
const wchar_t kSeparator = L'\\';
// copy input string because we'll be temporary modifying it in place
size_t length = wcslen(path);
wchar_t buffer[MAX_PATH];
memcpy( buffer, path, (length+1) * sizeof(path[0]) );
size_t i = 0;
std::wstring result;
// for network paths (\\server\share\RestOfPath), getting the display
// name mangles it into unusable form (e.g. "\\server\share" turns
// into "share on server (server)"). So detect this case and just skip
// up to two path components
if( length >= 2 && buffer[0] == kSeparator && buffer[1] == kSeparator )
{
int skippedCount = 0;
i = 2; // start after '\\'
while( i < length && skippedCount < 2 )
{
if( buffer[i] == kSeparator )
++skippedCount;
++i;
}
result.append( buffer, i );
}
// for drive names, just add it uppercased
else if( length >= 2 && buffer[1] == L':' )
{
result += towupper(buffer[0]);
result += L':';
if( length >= 3 && buffer[2] == kSeparator )
{
result += kSeparator;
i = 3; // start after drive, colon and separator
}
else
{
i = 2; // start after drive and colon
}
}
size_t lastComponentStart = i;
bool addSeparator = false;
while( i < length )
{
// skip until path separator
while( i < length && buffer[i] != kSeparator )
++i;
if( addSeparator )
result += kSeparator;
// if we found path separator, get real filename of this
// last path name component
bool foundSeparator = (i < length);
buffer[i] = 0;
SHFILEINFOW info;
// nuke the path separator so that we get real name of current path component
info.szDisplayName[0] = 0;
if( SHGetFileInfoW( buffer, 0, &info, sizeof(info), SHGFI_DISPLAYNAME ) )
{
result += info.szDisplayName;
}
else
{
// most likely file does not exist.
// So just append original path name component.
result.append( buffer + lastComponentStart, i - lastComponentStart );
}
// restore path separator that we might have nuked before
if( foundSeparator )
buffer[i] = kSeparator;
++i;
lastComponentStart = i;
addSeparator = true;
}
return result;
}
Again, thanks to cspirz for pointing me to SHGetFileInfo.
Have you tried using SHGetFileInfo?
There is another solution. First call GetShortPathName() and then GetLongPathName(). Guess what character case will be used then? ;-)
Just found that the Scripting.FileSystemObject suggested by #bugmagnet 10 years ago is a treasure. Unlike my old method, it works on Absolute Path, Relative Path, UNC Path and Very Long Path (path longer than MAX_PATH). Shame on me for not testing his method earlier.
For future reference, I would like to present this code which can be compiled in both C and C++ mode. In C++ mode, the code will use STL and ATL. In C mode, you can clearly see how everything is working behind the scene.
#include <Windows.h>
#include <objbase.h>
#include <conio.h> // for _getch()
#ifndef __cplusplus
# include <stdio.h>
#define SafeFree(p, fn) \
if (p) { fn(p); (p) = NULL; }
#define SafeFreeCOM(p) \
if (p) { (p)->lpVtbl->Release(p); (p) = NULL; }
static HRESULT CorrectPathCasing2(
LPCWSTR const pszSrc, LPWSTR *ppszDst)
{
DWORD const clsCtx = CLSCTX_INPROC_SERVER;
LCID const lcid = LOCALE_USER_DEFAULT;
LPCWSTR const pszProgId = L"Scripting.FileSystemObject";
LPCWSTR const pszMethod = L"GetAbsolutePathName";
HRESULT hr = 0;
CLSID clsid = { 0 };
IDispatch *pDisp = NULL;
DISPID dispid = 0;
VARIANT vtSrc = { VT_BSTR };
VARIANT vtDst = { VT_BSTR };
DISPPARAMS params = { 0 };
SIZE_T cbDst = 0;
LPWSTR pszDst = NULL;
// CoCreateInstance<IDispatch>(pszProgId, &pDisp)
hr = CLSIDFromProgID(pszProgId, &clsid);
if (FAILED(hr)) goto eof;
hr = CoCreateInstance(&clsid, NULL, clsCtx,
&IID_IDispatch, (void**)&pDisp);
if (FAILED(hr)) goto eof;
if (!pDisp) {
hr = E_UNEXPECTED; goto eof;
}
// Variant<BSTR> vtSrc(pszSrc), vtDst;
// vtDst = pDisp->InvokeMethod( pDisp->GetIDOfName(pszMethod), vtSrc );
hr = pDisp->lpVtbl->GetIDsOfNames(pDisp, NULL,
(LPOLESTR*)&pszMethod, 1, lcid, &dispid);
if (FAILED(hr)) goto eof;
vtSrc.bstrVal = SysAllocString(pszSrc);
if (!vtSrc.bstrVal) {
hr = E_OUTOFMEMORY; goto eof;
}
params.rgvarg = &vtSrc;
params.cArgs = 1;
hr = pDisp->lpVtbl->Invoke(pDisp, dispid, NULL, lcid,
DISPATCH_METHOD, ¶ms, &vtDst, NULL, NULL);
if (FAILED(hr)) goto eof;
if (!vtDst.bstrVal) {
hr = E_UNEXPECTED; goto eof;
}
// *ppszDst = AllocWStrCopyBStrFrom(vtDst.bstrVal);
cbDst = SysStringByteLen(vtDst.bstrVal);
pszDst = HeapAlloc(GetProcessHeap(),
HEAP_ZERO_MEMORY, cbDst + sizeof(WCHAR));
if (!pszDst) {
hr = E_OUTOFMEMORY; goto eof;
}
CopyMemory(pszDst, vtDst.bstrVal, cbDst);
*ppszDst = pszDst;
eof:
SafeFree(vtDst.bstrVal, SysFreeString);
SafeFree(vtSrc.bstrVal, SysFreeString);
SafeFreeCOM(pDisp);
return hr;
}
static void Cout(char const *psz)
{
printf("%s", psz);
}
static void CoutErr(HRESULT hr)
{
printf("Error HRESULT 0x%.8X!\n", hr);
}
static void Test(LPCWSTR pszPath)
{
LPWSTR pszRet = NULL;
HRESULT hr = CorrectPathCasing2(pszPath, &pszRet);
if (FAILED(hr)) {
wprintf(L"Input: <%s>\n", pszPath);
CoutErr(hr);
}
else {
wprintf(L"Was: <%s>\nNow: <%s>\n", pszPath, pszRet);
HeapFree(GetProcessHeap(), 0, pszRet);
}
}
#else // Use C++ STL and ATL
# include <iostream>
# include <iomanip>
# include <string>
# include <atlbase.h>
static HRESULT CorrectPathCasing2(
std::wstring const &srcPath,
std::wstring &dstPath)
{
HRESULT hr = 0;
CComPtr<IDispatch> disp;
hr = disp.CoCreateInstance(L"Scripting.FileSystemObject");
if (FAILED(hr)) return hr;
CComVariant src(srcPath.c_str()), dst;
hr = disp.Invoke1(L"GetAbsolutePathName", &src, &dst);
if (FAILED(hr)) return hr;
SIZE_T cch = SysStringLen(dst.bstrVal);
dstPath = std::wstring(dst.bstrVal, cch);
return hr;
}
static void Cout(char const *psz)
{
std::cout << psz;
}
static void CoutErr(HRESULT hr)
{
std::wcout
<< std::hex << std::setfill(L'0') << std::setw(8)
<< "Error HRESULT 0x" << hr << "\n";
}
static void Test(std::wstring const &path)
{
std::wstring output;
HRESULT hr = CorrectPathCasing2(path, output);
if (FAILED(hr)) {
std::wcout << L"Input: <" << path << ">\n";
CoutErr(hr);
}
else {
std::wcout << L"Was: <" << path << ">\n"
<< "Now: <" << output << ">\n";
}
}
#endif
static void TestRoutine(void)
{
HRESULT hr = CoInitialize(NULL);
if (FAILED(hr)) {
Cout("CoInitialize failed!\n");
CoutErr(hr);
return;
}
Cout("\n[ Absolute Path ]\n");
Test(L"c:\\uSers\\RayMai\\docuMENTs");
Test(L"C:\\WINDOWS\\SYSTEM32");
Cout("\n[ Relative Path ]\n");
Test(L".");
Test(L"..");
Test(L"\\");
Cout("\n[ UNC Path ]\n");
Test(L"\\\\VMWARE-HOST\\SHARED FOLDERS\\D\\PROGRAMS INSTALLER");
Cout("\n[ Very Long Path ]\n");
Test(L"\\\\?\\C:\\VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
L"VERYVERYVERYLOOOOOOOONGFOLDERNAME");
Cout("\n!! Worth Nothing Behavior !!\n");
Test(L"");
Test(L"1234notexist");
Test(L"C:\\bad\\PATH");
CoUninitialize();
}
int main(void)
{
TestRoutine();
_getch();
return 0;
}
Screenshot:
Old Answer:
I found that FindFirstFile() will return the proper casing file name (last part of path) in fd.cFileName. If we pass c:\winDOWs\exPLORER.exe as first parameter to FindFirstFile(), the fd.cFileName would be explorer.exe like this:
If we replace the last part of path with fd.cFileName, we will get the last part right; the path would become c:\winDOWs\explorer.exe.
Assuming the path is always absolute path (no change in text length), we can just apply this 'algorithm' to every part of path (except the drive letter part).
Talk is cheap, here is the code:
#include <windows.h>
#include <stdio.h>
/*
c:\windows\windowsupdate.log --> c:\windows\WindowsUpdate.log
*/
static HRESULT MyProcessLastPart(LPTSTR szPath)
{
HRESULT hr = 0;
HANDLE hFind = NULL;
WIN32_FIND_DATA fd = {0};
TCHAR *p = NULL, *q = NULL;
/* thePart = GetCorrectCasingFileName(thePath); */
hFind = FindFirstFile(szPath, &fd);
if (hFind == INVALID_HANDLE_VALUE) {
hr = HRESULT_FROM_WIN32(GetLastError());
hFind = NULL; goto eof;
}
/* thePath = thePath.ReplaceLast(thePart); */
for (p = szPath; *p; ++p);
for (q = fd.cFileName; *q; ++q, --p);
for (q = fd.cFileName; *p = *q; ++p, ++q);
eof:
if (hFind) { FindClose(hFind); }
return hr;
}
/*
Important! 'szPath' should be absolute path only.
MUST NOT SPECIFY relative path or UNC or short file name.
*/
EXTERN_C
HRESULT __stdcall
CorrectPathCasing(
LPTSTR szPath)
{
HRESULT hr = 0;
TCHAR *p = NULL;
if (GetFileAttributes(szPath) == -1) {
hr = HRESULT_FROM_WIN32(GetLastError()); goto eof;
}
for (p = szPath; *p; ++p)
{
if (*p == '\\' || *p == '/')
{
TCHAR slashChar = *p;
if (p[-1] == ':') /* p[-2] is drive letter */
{
p[-2] = toupper(p[-2]);
continue;
}
*p = '\0';
hr = MyProcessLastPart(szPath);
*p = slashChar;
if (FAILED(hr)) goto eof;
}
}
hr = MyProcessLastPart(szPath);
eof:
return hr;
}
int main()
{
TCHAR szPath[] = TEXT("c:\\windows\\EXPLORER.exe");
HRESULT hr = CorrectPathCasing(szPath);
if (SUCCEEDED(hr))
{
MessageBox(NULL, szPath, TEXT("Test"), MB_ICONINFORMATION);
}
return 0;
}
Advantages:
The code works on every version of Windows since Windows 95.
Basic error-handling.
Highest performance possible. FindFirstFile() is very fast, direct buffer manipulation makes it even faster.
Just C and pure WinAPI. Small executable size.
Disadvantages:
Only absolute path is supported, other are undefined behavior.
Not sure if it is relying on undocumented behavior.
The code might be too raw too much DIY for some people. Might get you flamed.
Reason behind the code style:
I use goto for error-handling because I was used to it (goto is very handy for error-handling in C). I use for loop to perform functions like strcpy and strchr on-the-fly because I want to be certain what was actually executed.
Okay, this is VBScript, but even so I'd suggest using the Scripting.FileSystemObject object
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Dim f
Set f = fso.GetFile("C:\testfile.dat") 'actually named "testFILE.dAt"
wscript.echo f.Name
The response I get is from this snippet is
testFILE.dAt
Hope that at least points you in the right direction.
FindFirstFileNameW will work with a few drawbacks:
it doesn't work on UNC paths
it strips the drive letter so you need to add it back
if there are more than one hard link to your file you need to identify the right one
After a quick test, GetLongPathName() does what you want.
Related
I'm trying to make a program that deletes a list of files one by one, using system().
The reason I'm using system() instead of remove() is because remove() doesn't support environment variables.
I've tried checking the return value, but my code seems to just always output that it's been deleted, even when it hasn't.
Code:
void fileLoop() {
std::vector<std::string> fileList = { "\"%userprofile%\\test.txt\"" };
while (!inter) {
for (int count = 0; count <= 0; count++) {
std::string moddedstring = "del /F " + fileList[count];
DWORD checker = GetFileAttributes((LPCWSTR)fileList[count].c_str());
if (checker == INVALID_FILE_ATTRIBUTES) {
goto next;
}
else {
system(moddedstring.c_str());
MessageBoxW(NULL, L"File found, successfully deleted", L"File Deleted", MB_OK | MB_ICONWARNING);
}
next:
std::cout << "\n";
}
Sleep(500);
}
}
I thought there is some easy way to find this out. I haven't found a way like that yet.
I will be adding more paths later.
Update:
I've tried using OpenProcessToken() with ExpandEnvironmentStringsForUserW() to add ENVs
But it complains that my buffer is of type LPCSTR* even when I set it to LPCSTR
Thanks!
A better way to get the user's profile path is to simply ask the OS directly, via SHGetFolderPath(CSIDL_PROFILE) or SHGetKnownFolderPath(FOLDERID_Profile).
Also, you should use DeleteFileA() instead of system("del"). There is no need to spawn an external console process when you can do the deletion directly. Also, because you are interested in error checking, which is much easier if you use the Win32 API directly.
Also, (LPCWSTR)fileList[count].c_str() will not work like you think. You can't convert a const char* to a const wchar_t* using a simple typecast. Drop the typecast and use GetFileAttributesA() instead.
Or, simply don't bother checking attributes at all. You can call DeleteFileA() unconditionally and let it tell you if it actually succeeded or failed.
With that said, try something more like this:
#include <shlobj.h>
std::string getUserProfilePath() {
CHAR szPath[MAX_PATH];
if (FAILED(SHGetFolderPathA(NULL, CSIDL_PROFILE, NULL, SHGFP_TYPE_CURRENT, szPath))) {
// error handling...
throw ...;
}
int len = lstrlenA(szPath);
szPath[len] = '\\';
return std::string(szPath, len + 1);
/*
PWSTR pszPath;
if (FAILED(SHGetKnownFolderPath(FOLDERID_Profile, KF_FLAG_DEFAULT, NULL, &pszPath))) {
// error handling...
throw ...;
}
int wlen = lstrlenW(pszPath);
int len = WideCharToMultiByte(0, 0, pszPath, wlen, NULL, 0, NULL, NULL);
if (len == 0) {
// error handling...
throw ...;
}
std::vector<CHAR> buffer(len + 1);
len = WideCharToMultiByte(CP_ACP, 0, pszPath, wlen, buffer.data(), len, NULL, NULL);
if (len == 0) {
// error handling...
throw ...;
}
buffer[len] = '\\';
CoTaskMemFree(pszPath);
return std::wstring(buffer.data(), buffer.size());
*/
}
void fileLoop() {
std::vector<std::string> fileList = { getUserProfilePath() + "test.txt" };
while (!inter) {
for (size_t count = 0; count < fileList.size(); ++count) {
if (DeleteFileA(fileList[count].c_str())) {
MessageBoxW(NULL, L"File found, successfully deleted", L"File Deleted", MB_OK | MB_ICONWARNING);
} else {
// error handling...
}
std::cout << "\n";
}
Sleep(500);
}
}
Alternatively, using Unicode strings instead (which you really should use when interacting with the filesystem):
#include <shlobj.h>
std::wstring getUserProfilePath() {
WCHAR szPath[MAX_PATH];
if (FAILED(SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, SHGFP_TYPE_CURRENT, szPath))) {
// error handling...
throw ...;
}
int len = lstrlenW(szPath);
szPath[len] = '\\';
return std::wstring(szPath, len + 1);
/*
PWSTR pszPath;
if (FAILED(SHGetKnownFolderPath(FOLDERID_Profile, KF_FLAG_DEFAULT, NULL, &pszPath))) {
// error handling...
throw ...;
}
int len = lstrlenW(pszPath);
std::wstring sPath(len + 1, '\0');
std::copy(pszPath, pszPath + len, sPath.begin());
sPath[len] = '\\';
CoTaskMemFree(pszPath);
return sPath;
*/
}
void fileLoop() {
std::vector<std::wstring> fileList = { getUserProfilePath() + L"test.txt" };
while (!inter) {
for (size_t count = 0; count < fileList.size(); ++count) {
if (DeleteFileW(fileList[count].c_str())) {
MessageBoxW(NULL, L"File found, successfully deleted", L"File Deleted", MB_OK | MB_ICONWARNING);
} else {
// error handling...
}
std::cout << "\n";
}
Sleep(500);
}
}
Even better, if you are using C++17 or later, consider using the <filesystem> library instead:
#include <shlobj.h>
#include <filesystem>
using fs = std::filesystem;
fs::path getUserProfilePath() {
WCHAR szPath[MAX_PATH];
if (FAILED(SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, SHGFP_TYPE_CURRENT, szPath))) {
// error handling...
throw ...;
}
return szPath;
/*
PWSTR pszPath;
if (FAILED(SHGetKnownFolderPath(FOLDERID_Profile, KF_FLAG_DEFAULT, NULL, &pszPath))) {
// error handling...
throw ...;
}
fs::path pth(pszPath);
CoTaskMemFree(pszPath);
return pth;
*/
}
void fileLoop() {
std::vector<fs::path> fileList = { getUserProfilePath() / L"test.txt" };
while (!inter) {
for (auto &pth : fileList) {
std::error_code ec;
if (fs::remove(pth, ec)) {
MessageBoxW(NULL, L"File found, successfully deleted", L"File Deleted", MB_OK | MB_ICONWARNING);
} else {
// error handling...
}
std::cout << "\n";
}
Sleep(500);
}
}
So all I want in life is to have a program where I can say "Hey Computer" and it responds with "Hello". So I set myself upon the task and after some research produced the code below yet whenever I try to compile it through Visual Studio 2017 on Windows 10 I get this error: 'GetVersionExA': was declared deprecated but I don't understand because I don't call that function anywhere in my code.
#include <sphelper.h>
#include <sapi.h>
#include <iostream>
#include <string>
#include <vector>
#include <locale>
const ULONGLONG grammarId = 0;
const wchar_t* ruleName1 = L"ruleName1";
int start_listening(const std::string& word);
ISpRecoGrammar* init_grammar(ISpRecoContext* recoContext, const std::string& command);
void get_text(ISpRecoContext* reco_context);
void check_result(const HRESULT& result);
ISpVoice * pVoice = NULL;
HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice);
inline std::wstring s2w(const std::string &s, const std::locale &loc = std::locale())
{
typedef std::ctype<wchar_t> wchar_facet;
std::wstring return_value;
if (s.empty())
{
return return_value;
}
if (std::has_facet<wchar_facet>(loc))
{
std::vector<wchar_t> to(s.size() + 2, 0);
std::vector<wchar_t>::pointer toPtr = &to[0];
const wchar_facet &facet = std::use_facet<wchar_facet>(loc);
if (0 != facet.widen(s.c_str(), s.c_str() + s.size(), toPtr))
{
return_value = to.data();
}
}
return return_value;
}
int main(int argc, char** argv)
{
HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice);
std::string hello = "hello";
start_listening("Hey computer");
hr = pVoice->Speak(s2w(hello).c_str(), 0, NULL);
return EXIT_SUCCESS;
}
// This function exits when the word passed as parameter is said by the user
int start_listening(const std::string& word)
{
// Initialize COM library
if (FAILED(::CoInitialize(nullptr))) {
return EXIT_FAILURE;
}
std::cout << "You should start Windows Recognition" << std::endl;
std::cout << "Just say \"" << word << "\"" << std::endl;
HRESULT hr;
ISpRecognizer* recognizer;
hr = CoCreateInstance(CLSID_SpSharedRecognizer,
nullptr, CLSCTX_ALL, IID_ISpRecognizer,
reinterpret_cast<void**>(&recognizer));
check_result(hr);
ISpRecoContext* recoContext;
hr = recognizer->CreateRecoContext(&recoContext);
check_result(hr);
// Disable context
hr = recoContext->Pause(0);
check_result(hr);
ISpRecoGrammar* recoGrammar = init_grammar(recoContext, word);
hr = recoContext->SetNotifyWin32Event();
check_result(hr);
HANDLE handleEvent;
handleEvent = recoContext->GetNotifyEventHandle();
if (handleEvent == INVALID_HANDLE_VALUE) {
check_result(E_FAIL);
}
ULONGLONG interest;
interest = SPFEI(SPEI_RECOGNITION);
hr = recoContext->SetInterest(interest, interest);
check_result(hr);
// Activate Grammar
hr = recoGrammar->SetRuleState(ruleName1, 0, SPRS_ACTIVE);
check_result(hr);
// Enable context
hr = recoContext->Resume(0);
check_result(hr);
// Wait for reco
HANDLE handles[1];
handles[0] = handleEvent;
WaitForMultipleObjects(1, handles, FALSE, INFINITE);
get_text(recoContext);
std::cout << "Hello user" << std::endl;
recoGrammar->Release();
::CoUninitialize();
system("PAUSE");
return EXIT_SUCCESS;
}
/**
* Create and initialize the Grammar.
* Create a rule for the grammar.
* Add word to the grammar.
*/
ISpRecoGrammar* init_grammar(ISpRecoContext* recoContext, const std::string& command)
{
HRESULT hr;
SPSTATEHANDLE sate;
ISpRecoGrammar* recoGrammar;
hr = recoContext->CreateGrammar(grammarId, &recoGrammar);
check_result(hr);
WORD langId = MAKELANGID(LANG_FRENCH, SUBLANG_FRENCH);
hr = recoGrammar->ResetGrammar(langId);
check_result(hr);
// TODO: Catch error and use default langId => GetUserDefaultUILanguage()
// Create rules
hr = recoGrammar->GetRule(ruleName1, 0, SPRAF_TopLevel | SPRAF_Active, true, &sate);
check_result(hr);
// Add a word
const std::wstring commandWstr = std::wstring(command.begin(), command.end());
hr = recoGrammar->AddWordTransition(sate, NULL, commandWstr.c_str(), L" ", SPWT_LEXICAL, 1, nullptr);
check_result(hr);
// Commit changes
hr = recoGrammar->Commit(0);
check_result(hr);
return recoGrammar;
}
void get_text(ISpRecoContext* reco_context)
{
const ULONG maxEvents = 10;
SPEVENT events[maxEvents];
ULONG eventCount;
HRESULT hr;
hr = reco_context->GetEvents(maxEvents, events, &eventCount);
// Warning hr equal S_FALSE if everything is OK
// but eventCount < requestedEventCount
if (!(hr == S_OK || hr == S_FALSE)) {
check_result(hr);
}
ISpRecoResult* recoResult;
recoResult = reinterpret_cast<ISpRecoResult*>(events[0].lParam);
wchar_t* text;
hr = recoResult->GetText(SP_GETWHOLEPHRASE, SP_GETWHOLEPHRASE, FALSE, &text, NULL);
check_result(hr);
CoTaskMemFree(text);
}
void check_result(const HRESULT& result)
{
if (result == S_OK) {
return;
}
std::string message;
switch (result) {
case E_INVALIDARG:
message = "One or more arguments are invalids.";
case E_ACCESSDENIED:
message = "Acces Denied.";
case E_NOINTERFACE:
message = "Interface does not exist.";
case E_NOTIMPL:
message = "Not implemented method.";
case E_OUTOFMEMORY:
message = "Out of memory.";
case E_POINTER:
message = "Invalid pointer.";
case E_UNEXPECTED:
message = "Unexpecter error.";
case E_FAIL:
message = "Failure";
default:
message = "Unknown : " + std::to_string(result);
}
throw std::exception(message.c_str());
}
It is suppressable with a pragma:
#pragma warning(disable:4996)
#include <sphelper.h>
#pragma warning(default: 4996)
GetVersionEx is being used by the header sphelper.h which you're including. It's using it to check that the function SpGetDescription() is running on Vista or later. You could probably work around this issue by targeting the 8.1 SDK version instead of 10. However, it's bad that the shipped MS SAPI API in the Windows 10 SDK is using functions which are deprecated in Windows 10.. I'd say this is a MS issue.
Alternately this would work:
#define FKG_FORCED_USAGE 1
#include <sphelper.h>
#undef FKG_FORCED_USAGE
If any kind soul out there please go through following source and tell me why MSXML "load" function fails to load this XML.
Here i'm trying to load a UTF-8 encoded XML using MSXML parser's "load" function. And i have a BSTR [UTF-16 encoded] as an argument, so i'm trying to convert it, into a SAFEARRAY of bytes so that i can passed it into the "load" function of MSXML. But the issue is load function failed to load this XML. If anyone could provide a solution to i would be really grateful.
#include <windows.h>
#include <objsafe.h>
#include <objbase.h>
#include <atlbase.h>
#include <string>
#include <comutil.h>
#include <msxml2.h>
#include <iostream>
using namespace std;
#define STATUS_SUCCESS 0
#define STATUS_FAIL -1
long LoadXmlData(BSTR xmlDoc)
{
HRESULT hr = S_OK;
CComPtr <IXMLDOMDocument> xmlDomDoc = NULL;
CComPtr <IXMLDOMElement> docRoot = NULL;
VARIANT_BOOL isParseSucess = FALSE;
CoInitialize(NULL);
hr = xmlDomDoc.CoCreateInstance(__uuidof(DOMDocument30));
if (FAILED(hr))
{
return STATUS_FAIL;
}
BYTE HUGEP *pByte;
int len = WideCharToMultiByte(CP_UTF8, 0, xmlDoc, -1, NULL, 0, NULL, NULL);
SAFEARRAYBOUND rgsabound[1];
rgsabound[0].cElements = len;
rgsabound[0].lLbound = 0;
SAFEARRAY* psa = SafeArrayCreate(VT_UI1, 1, rgsabound);
if (psa != NULL)
{
hr = SafeArrayAccessData(psa, (void HUGEP**)&pByte);
if (!FAILED(hr))
{
if (len > 0)
{
WideCharToMultiByte(CP_UTF8, 0, xmlDoc, -1, (LPSTR)&pByte[0], len, NULL, NULL);
//cout << "Converted Byte Array: " << pByte << endl << endl;
}
else
{
return STATUS_FAIL;
}
SafeArrayUnaccessData(psa);
}
}
VARIANT v;
VariantInit(&v);
V_VT(&v) = VT_ARRAY | VT_UI1;
V_ARRAY(&v) = psa;
hr = xmlDomDoc->load(v, &isParseSucess);
//hr = xmlDomDoc->loadXML(xmlDoc, &isParseSucess); //can't use this function because XML is encoded in UTF-8
if (FAILED(hr) || (!isParseSucess))
{
return STATUS_FAIL;
}
else
{
return STATUS_SUCCESS;
}
}
int main()
{
BSTR xmlDoc = SysAllocString(L"<?xml version=\"1.0\" encoding=\"UTF-8\"?> <response> </response> ");
long ret = LoadXmlData(xmlDoc);
if (ret == STATUS_SUCCESS)
{
cout << "MSXML: loading the XML succeeded";
}
else
{
cout << "MSXML: loading the XML failed";
}
//string str;
//getline(cin, str);
return 0;
}
ps: If anyone try to compile this source you may get a link error first time, add comsuppw.lib as a linker dependency in VS settings. And XML is UTF-8 encoded, so i can't use "LoadXML" function in MSXML.
XML files are UTF-8 but there is no conversion needed here because Windows functions will automatically convert between UTF-16 and UTF-8 when needed (unless input/output is BYTE*...)
BSTR needs cleanup. You can use CComBSTR(str) which has automatic cleanup.
You can use const wchar_t* to pass strings to your own functions. BSTR is required for COM etc.
As noted in comments, IXMLDOMDocument::load expects a file name as input. Use IXMLDOMDocument::loadXML in this case.
#include <iostream>
#include <windows.h>
#include <atlbase.h>
#include <msxml2.h>
long LoadXmlData(const wchar_t* content)
{
HRESULT hr = S_FALSE;
CComPtr<IXMLDOMDocument> doc = NULL;
CComPtr<IXMLDOMElement> docRoot = NULL;
hr = doc.CoCreateInstance(__uuidof(DOMDocument30));
if(FAILED(hr))
return S_FALSE;
VARIANT_BOOL is_success = FALSE;
CComBSTR arg(content);
hr = doc->loadXML(arg, &is_success);
//if you are loading from a file:
//hr = doc->load(CComVariant(L"c:\\test\\test.xml"), &is_success);
if(FAILED(hr) || !is_success)
return S_FALSE;
//if save is needed:
//doc->save(CComVariant(L"c:\\test\\test.xml"));
return S_OK;
}
int main()
{
CoInitialize(NULL);
//ελληνική γλώσσα Greek text for testing
CComBSTR data(L"<?xml version=\"1.0\" encoding=\"UTF-8\"?><response>ελληνική γλώσσα</response>");
long ret = LoadXmlData(data);
if(ret == S_OK)
std::cout << "MSXML: loading the XML succeeded\n";
else
std::cout << "MSXML: loading the XML failed\n";
CoUninitialize();
return 0;
}
I ran into an extremely weird issue today when messing around with the parsing the Windows Portable Executable file structure today. Specifically in the Export table.
I found myself getting a Stack Overflow (so this seemed like the most appropriate QA board) when trying to resolve the function address of an Exported function in a DLL.
I've written my own version of GetProcAddress which does the parsing manually rather than calling the existing GetProcAddress method. Please don't just tell me to use the existing GetProcAddress method, it's not suitable for my current situation and I want to learn something from this.
For most of the situations I encounter, my version has worked admirably and hasn't hit any issues. However the function was tested against a DLL named API-MS-Win-Core-ProcessThreads-L1-1-0.dll (as part of a recursive parse of Kernel32.dll) and this is when the StackOverflow occurred.
I've narrowed it down to the following function exported from API-MS-Win-Core-ProcessThreads-L1-1-0.dll:
CreateRemoteThreadEx
Now, this exported function is actually a forwarded export. Usually this is no worries; I've written my function so that it should handle forwarded exports. However this function is forwarded to
api-ms-win-core-processthreads-l1-1-0.CreateRemoteThreadEx
Anyone seeing the problem here? Stepping through the code, my GetProcAddress function then calls LoadLibrary on api-ms-win-core-processthreads-l1-1-0 and then attempts to recursively lookup CreateRemoteThreadEx. On the very next iteration, however, the CreateRemoteThreadEx function is again forwarded... to
api-ms-win-core-processthreads-l1-1-0.CreateRemoteThreadEx
And so begins the StackOverflow. After a bit more investigation I found that the result of calling
LoadLibraryA("api-ms-win-core-processthreads-l1-1-0");
Returns the same result as
LoadLibraryA("kernel32.dll");
I'm stumped.
Here's my current code:
#include <Windows.h>
#define MKPTR(p1,p2) ((DWORD_PTR)(p1) + (DWORD_PTR)(p2))
INT LookupExport(IMAGE_DOS_HEADER* pDosHd, DWORD* pNames, DWORD nNames, LPCSTR lpProcName)
{
// Do a binary search on the name pointer table
INT start = 0,
index = -1,
middle = -1,
end = nNames - 1,
cmp = 0;
CHAR *pName;
while (start <= end && index == -1)
{
middle = (start + end) >> 1;
pName = (CHAR*)MKPTR(pDosHd, pNames[middle]);
if ((cmp = strcmp(pName, lpProcName)) == 0)
index = middle; // found
else if (cmp < 0)
start = middle + 1;
else
end = middle;
}
return index;
}
FARPROC InternalGetProcAddress(HMODULE hModule, LPCSTR lpProcName)
{
BOOL ordinalSearch = HIWORD(lpProcName) == 0;
WORD ordinal = 0;
IMAGE_DOS_HEADER *pDosHd = (IMAGE_DOS_HEADER*)hModule;
if (pDosHd->e_magic != IMAGE_DOS_SIGNATURE)
return NULL;
IMAGE_NT_HEADERS *pNtHd = (IMAGE_NT_HEADERS*)MKPTR(pDosHd, pDosHd->e_lfanew);
if (pNtHd->Signature != IMAGE_NT_SIGNATURE)
return NULL;
IMAGE_DATA_DIRECTORY directory = pNtHd->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
if (directory.Size == 0 || directory.VirtualAddress == 0)
return NULL;
IMAGE_EXPORT_DIRECTORY *pExports = (IMAGE_EXPORT_DIRECTORY*)MKPTR(pDosHd, directory.VirtualAddress);
if (!ordinalSearch)
{
INT index = LookupExport(pDosHd, (DWORD*)MKPTR(pDosHd, pExports->AddressOfNames), pExports->NumberOfNames, lpProcName);
if (index == -1)
return NULL;
ordinal = ((WORD*)MKPTR(pDosHd, pExports->AddressOfNameOrdinals))[index];
}
else
{
ordinal = LOWORD(lpProcName);
}
INT delta = pExports->Base - 1;
DWORD dwAddress = ((DWORD*)MKPTR(pDosHd, pExports->AddressOfFunctions))[ordinal - delta];
// Check whether forwarded:
if (dwAddress >= directory.VirtualAddress && dwAddress < (directory.VirtualAddress + directory.Size))
{
CHAR pForward[256];
strcpy(pForward, (CHAR*)MKPTR(pDosHd, dwAddress));
CHAR *pFunction = strchr(pForward, '.');
if (pFunction == NULL)
return NULL;
// break into seperate parts and recurse
*pFunction++ = 0;
return InternalGetProcAddress(LoadLibraryA(pForward), pFunction);
}
return (FARPROC)MKPTR(hModule, dwAddress);
}
Any insight would be greatly appreciated.
Okay after following #sergmat's advice I took a look at the API Set documentation (found here for anyone interested). I've now modified my GetProcAddress code to do a naive lookup of the Api Set table.
#include <Windows.h>
#define MKPTR(p1,p2) ((DWORD_PTR)(p1) + (DWORD_PTR)(p2))
typedef struct _stripped_peb32 {
BYTE unused1[0x038];
PVOID ApiSet;
BYTE unused2[0x1AC];
} PEB32;
typedef struct _stripped_peb64 {
BYTE unused1[0x068];
PVOID ApiSet;
BYTE unused2[0x23C];
} PEB64;
typedef struct _PROCESS_BASIC_INFORMATION {
PVOID Reserved1;
LPVOID PebBaseAddress;
PVOID Reserved2[2];
ULONG_PTR UniqueProcessId;
PVOID Reserved3;
} PROCESS_BASIC_INFORMATION;
typedef struct _api_set_host {
DWORD ImportModuleName;
WORD ImportModuleNameLength;
DWORD HostModuleName;
WORD HostModuleNameLength;
} API_SET_HOST;
typedef struct _api_set_host_descriptor {
DWORD NumberOfHosts;
API_SET_HOST Hosts[1];
} API_SET_HOST_DESCRIPTOR;
typedef struct _api_set_entry {
DWORD Name;
WORD NameLength;
DWORD HostDescriptor;
} API_SET_ENTRY;
typedef struct _api_set_header {
DWORD unknown1;
DWORD NumberOfEntries;
API_SET_ENTRY Entries[1];
} API_SET_HEADER;
typedef NTSTATUS (__stdcall *fnNtQueryInformationProcess)(HANDLE ProcessHandle, DWORD ProcessInformationClass, PVOID ProcessInformation, ULONG ProcessInformationLength, PULONG ReturnLength);
API_SET_HEADER *GetApiSetHeader()
{
fnNtQueryInformationProcess NtQueryInformationProcess = (fnNtQueryInformationProcess)GetProcAddress(LoadLibraryW(L"ntdll.dll"), "NtQueryInformationProcess");
if (!NtQueryInformationProcess)
return NULL;
PROCESS_BASIC_INFORMATION info;
if (NtQueryInformationProcess(GetCurrentProcess(), 0, &info, sizeof(info), NULL) != S_OK)
return NULL;
#if defined(_WIN32)
return (API_SET_HEADER*)(((PEB32*)info.PebBaseAddress)->ApiSet);
#elif defined(_WIN64)
return (API_SET_HEADER*)(((PEB64*)info.PebBaseAddress)->ApiSet);
#else
return NULL; // unsupported architecture
#endif
}
HMODULE ResolveImportMap(LPCSTR lpModuleName)
{
API_SET_HEADER *pHeader = GetApiSetHeader();
if (pHeader == NULL)
return NULL;
API_SET_ENTRY *pEntry = pHeader->Entries;
API_SET_HOST_DESCRIPTOR* pDescriptor;
wchar_t module[128];
// First, normalize the LPCSTR, the API Set table doesn't have the API- prefix
if (strnicmp("api-", lpModuleName, 4) == 0)
lpModuleName += 4;
// Next convert the LPCSTR to a unicode string for comparison and remove the extension (if found)
mbstowcs(module, lpModuleName, sizeof(module) / sizeof(wchar_t));
wchar_t *dot = wcsrchr(module, L'.');
if (dot) *dot = L'\0';
// Begin the lookup:
// todo: implement a case-insensitive binary search, not much to be gained for the effort IMO as there's
// only 35 entries in the current version of Windows 7, but the option is there for performance nuts.
for(unsigned long i = 0; i < pHeader->NumberOfEntries; ++i, ++pEntry)
{
// Check the top-level host map
if (wcsnicmp(module, (const wchar_t*)MKPTR(pHeader, pEntry->Name), pEntry->NameLength) == 0)
{
pDescriptor = (API_SET_HOST_DESCRIPTOR*)MKPTR(pHeader, pEntry->HostDescriptor);
// iterate backwards through the hosts to find the most important one (I think this is naive)
for(unsigned long j = pDescriptor->NumberOfHosts; j > 0; --j)
{
if (pDescriptor->Hosts[j - 1].HostModuleNameLength)
{
memcpy(module, (const void*)MKPTR(pHeader, pDescriptor->Hosts[j - 1].HostModuleName), pDescriptor->Hosts[j - 1].HostModuleNameLength);
module[pDescriptor->Hosts[j - 1].HostModuleNameLength / sizeof(wchar_t)] = L'\0';
return GetModuleHandleW(module); // All the modules should already be loaded, so use GetModuleHandle rather than LoadLibrary
}
}
}
}
return NULL;
}
INT LookupExport(IMAGE_DOS_HEADER* pDosHd, DWORD* pNames, DWORD nNames, LPCSTR lpProcName)
{
// Do a binary search on the name pointer table
INT start = 0,
index = -1,
middle = -1,
end = nNames - 1,
cmp = 0;
CHAR *pName;
while (start <= end && index == -1)
{
middle = (start + end) >> 1;
pName = (CHAR*)MKPTR(pDosHd, pNames[middle]);
if ((cmp = strcmp(pName, lpProcName)) == 0)
index = middle;
else if (cmp < 0)
start = middle + 1;
else
end = middle;
}
return index;
}
FARPROC InternalGetProcAddress(HMODULE hModule, LPCSTR lpProcName)
{
if (hModule == NULL)
return NULL;
BOOL ordinalSearch = HIWORD(lpProcName) == 0;
WORD ordinal = 0;
IMAGE_DOS_HEADER *pDosHd = (IMAGE_DOS_HEADER*)hModule;
if (pDosHd->e_magic != IMAGE_DOS_SIGNATURE)
return NULL;
IMAGE_NT_HEADERS *pNtHd = (IMAGE_NT_HEADERS*)MKPTR(pDosHd, pDosHd->e_lfanew);
if (pNtHd->Signature != IMAGE_NT_SIGNATURE)
return NULL;
IMAGE_DATA_DIRECTORY directory = pNtHd->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
if (directory.Size == 0 || directory.VirtualAddress == 0)
return NULL;
IMAGE_EXPORT_DIRECTORY *pExports = (IMAGE_EXPORT_DIRECTORY*)MKPTR(pDosHd, directory.VirtualAddress);
if (!ordinalSearch)
{
INT index = LookupExport(pDosHd, (DWORD*)MKPTR(pDosHd, pExports->AddressOfNames), pExports->NumberOfNames, lpProcName);
if (index == -1)
return NULL;
ordinal = ((WORD*)MKPTR(pDosHd, pExports->AddressOfNameOrdinals))[index];
}
else
{
ordinal = LOWORD(lpProcName);
}
INT ordbase = pExports->Base - 1;
DWORD dwAddress = ((DWORD*)MKPTR(pDosHd, pExports->AddressOfFunctions))[ordinal - ordbase];
// Check whether forwarded:
if (dwAddress >= directory.VirtualAddress && dwAddress < (directory.VirtualAddress + directory.Size))
{
CHAR pForward[256];
strcpy(pForward, (CHAR*)MKPTR(pDosHd, dwAddress));
CHAR *pFunction = strchr(pForward, '.');
if (pFunction == NULL)
return NULL;
// break into seperate parts and recurse
*pFunction++ = 0;
// check if ordinal-forwarded
if (*pFunction == '#')
pFunction = (PSTR)(unsigned short)(atoi(++pFunction));
HMODULE hDestination = LoadLibraryA(pForward);
// detect an infinite loop, the forward declaration requests the same module handle with
// the same function lookup, this could be an Api Set (Windows7+)
if (hDestination == hModule && (ordinalSearch ? LOWORD(pFunction) == LOWORD(lpProcName) : strcmp(pFunction, lpProcName) == 0))
hDestination = ResolveImportMap(pForward); // ResolveImportMap will return NULL if not an API Set and so avoid infinite recursion
return InternalGetProcAddress(hDestination, pFunction);
}
return (FARPROC)MKPTR(hModule, dwAddress);
}
I'm using C++ without .NET on Win32, how can I download an image over HTTP from a website without having to re-invent the wheel? Is there an API or library that provides a single function to do this?
http://mywebsite/file.imgext --> C:\path\to\dir\file.imgext
WinInet APIs are easier than you think
Here is a complete win32 console program. Can be built with with VS 2010 Express and down loading windows SDK to get WinInit.
// imaged.cpp : Defines the entry point for the console application.
//
// Copy file from internet onto local file
// Uses Wininet API
// program takes 1 mandatory command line argument - URL string
// it downloads ito the current directory, or whatever is passed
// as the second parameter to DownloadURLImage.
// optional parameter, the name of the file (excluding path), by default it uses the
// filename from the URL string.
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <WinInet.h> // from SDK
#include "string.h"
//#include<TCHAR.H>
//#include "Tchar.h"
using namespace std ;
int convertURLtofname (TCHAR * szURL, TCHAR * szname )
// extract the filename from the URL
{
char aszfilename [100];
HRESULT result;
char achar[3], aszURL [100];
size_t nchars, i, j;
int fresult;
fresult = 0;
nchars= _tcslen(szURL);
i= nchars -1;
while ((i > 0) && (szURL[i] != '/') && (szURL[i] != '\\')) {i--;}
j= 0; i++;
while (i < nchars) { szname [j++]= szURL[i++]; }
szname[j]=_T('\0');
// wcstombs ( aszfilename, szname, 100 );
// cout << aszfilename << endl;
//----------------------------------------------
return fresult ;
}
int determinepathfilename (TCHAR * szURL, TCHAR * szpath, TCHAR * szname, TCHAR * szpathfilename)
{
// use path and filename when supplied. If filename (e.g. funkypic.jpg) is not supplied, then the
// filename will be extracted from the last part of the URL
int result ;
result= 0;
TCHAR szname_copy [100] ;
if ((szname == NULL) || (szname[0] == '\0'))
convertURLtofname (szURL, szname_copy);
else
_tcscpy (szname_copy, szname);
if ((szpath == NULL) || (szpath[0] == '\0'))
_tcscpy (szpathfilename, szname_copy);
else
{
_tcscpy (szpathfilename, szpath);
_tcscat (szpathfilename, szname_copy);
}
return result ;
}
bool GetFile (HINTERNET hOpen, // Handle from InternetOpen()
TCHAR *szURL, // Full URL
TCHAR * szpath,
TCHAR * szname)
{
DWORD dwSize;
TCHAR szHead[15];
BYTE * szTemp[1024];
HINTERNET hConnect;
FILE * pFile;
TCHAR szpathfilename [100] ;
szHead[0] = '\0';
if ( !(hConnect = InternetOpenUrl( hOpen, szURL, szHead, 15, INTERNET_FLAG_DONT_CACHE, 0)))
{
std::cout << "Error: InternetOpenUrl" << std::endl;
return 0;
}
determinepathfilename (szURL, szpath, szname, szpathfilename);
if ( !(pFile = _tfopen (szpathfilename, _T("wb") ) ) )
{
std::cerr << "Error _tfopen" << std::endl;
return false;
}
do
{
// Keep copying in 1024 bytes chunks, while file has any data left.
// Note: bigger buffer will greatly improve performance.
if (!InternetReadFile (hConnect, szTemp, 1024, &dwSize) )
{
fclose (pFile);
std::cerr << "Error InternetReadFile" << std::endl;
return FALSE;
}
if (!dwSize)
break; // Condition of dwSize=0 indicate EOF. Stop.
else
fwrite(szTemp, sizeof (BYTE), dwSize , pFile);
} // do
while (TRUE);
fflush (pFile);
fclose (pFile);
return TRUE;
}
int DownloadURLImage (TCHAR * szURL, TCHAR * szpath, TCHAR * szname)
{ int result ;
HINTERNET hInternet;
result= 0;
hInternet= InternetOpen (_T("imaged"),
INTERNET_OPEN_TYPE_DIRECT, //__in DWORD dwAccessType
NULL, //__in LPCTSTR lpszProxyName,
NULL, //__in LPCTSTR lpszProxyBypass,
NULL //_in DWORD dwFlags
);
GetFile (hInternet, szURL, szpath, szname) ;
InternetCloseHandle(hInternet);
return result ;
}
int _tmain(int argc, _TCHAR* argv[])
{
if (argc == 2)
{
DownloadURLImage (argv[1], NULL, NULL);
//DownloadURLImage (argv[1], _T"C:/", NULL);
}
else if (argc == 3)
{
DownloadURLImage (argv[1], NULL, argv[2]);
//DownloadURLImage (argv[1], _T"C:/", argv[2]);
}
else
{
cout << "Usage: imaged <image URL>" << endl ;
}
system("pause") ;
return 0;
}
You could use cURLpp
I havn't used it yet, but example20 looks like it could solve your problem.
If you want an EASY solution, use this amazingly simple one liner:
system("C:\\Path\\To\\Wget\\wget.exe http://pixelcaster.com/yosemite/webcams/ahwahnee2.jpg -O C:\\Users\\Me\\Desktop\\ahwahnee2.jpg");
With wget for windows
choco install wget
See chocolatey.org
Use Windows Http Services API.
You could use the WinInet or WinHTTP classes in C++. These are native Win32 APIs the abstract some of the work of getting sending and receiving files from the Internet.
I've used WinInet with great success to do just what you're trying to do.
If starting a new process is ok, you could have a look at WGET. (And even if not, the sources are available; you can look there to see how it's been implemented.)
Using POCO for this now. :-)