1
votes

I'm trying to prompt the user to enter a filename/path at the console and then attempt to open this file using CreateFile(). At the moment, the call to CreateFile() works if i use a hardcoded filename and the TEXT() macro. However, upon passing it user input the call fails and GetLastError() returns error 123 or "The filename, directory name, or volume label syntax is incorrect". Below is the relevant code, I'm pretty lost as to why this is happening.

LPTSTR dllPath;
LPDWORD dllPathLength;
dllPath = (LPTSTR)calloc(MAX_PATH, sizeof(TCHAR));
dllPathLength = new DWORD;
if(ReadConsole(hStdIn, dllPath, MAX_PATH, dllPathLength, NULL)==0)
{
    _tprintf(TEXT("ReadConsole failed with error %d\n"), GetLastError());
    return 1;
}


_tprintf(TEXT("File path entered: %s\n"), dllPath);

hDll = CreateFile(dllPath, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, NULL, NULL);
if (hDll == INVALID_HANDLE_VALUE)
{
    _tprintf(TEXT("CreateFile failed with error %d\n"), GetLastError());
    return 1;
}

For reference, to make it work with the hardcoded file path I replaced the "dllPath" parameter in the call to CreateFile() with "TEXT("C:\log.log")".

Any help would be much appreciated! Apologies in advance if this is an obvious mistake, i'm still trying to get used to Windows-style C programming, and never was very good with the regular style either.

1
By the way, there's little reason to use the TCHAR macros and friends these days, Win95 is long dead, and all currently supported Win32 OSs do UNICODE just fine; you can just use WCHAR/wprintf/LPWSTR/L"" directly instead. Also, for dllPathLength, you don't need to allocate memory for this, just use a DWORD variable directly: declare DWORD dwDllPathLength = 0; and pass &dwDllPathLength as the parameter. - BrendanMcK

1 Answers

3
votes

Try this:

TCHAR dllPath[MAX_PATH+1] = {0}; 
DWORD dllPathLength = 0; 
if(!ReadConsole(hStdIn, dllPath, MAX_PATH, &dllPathLength, NULL)) 
{ 
    _tprintf(TEXT("ReadConsole failed with error %u\n"), GetLastError()); 
    return 1; 
} 

_tprintf(TEXT("File path entered: %s\n"), dllPath); 

hDll = CreateFile(dllPath, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, NULL, NULL); 
if (hDll == INVALID_HANDLE_VALUE) 
{ 
    _tprintf(TEXT("CreateFile failed with error %u\n"), GetLastError()); 
    return 1; 
} 

If that still does not work, then make sure ReadConsole() is not including a line break or other terminator at the end of the returned path to make it invalid. If it is, you will have to strip it off before calling CreateFile().