使用Win32 API读取用户指定的文件

Reading a user-specified file with the Win32 API

本文关键字:文件 用户 Win32 API 读取 使用      更新时间:2023-10-16

我试图提示用户在控制台输入文件名/路径,然后尝试使用CreateFile()打开该文件。目前,如果我使用硬编码的文件名和TEXT()宏,则对CreateFile()的调用可以工作。然而,在传递用户输入时,调用失败,GetLastError()返回错误123或"文件名、目录名或卷标语法不正确"。下面是相关的代码,我很不明白为什么会发生这种情况。

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 %dn"), GetLastError());
    return 1;
}

_tprintf(TEXT("File path entered: %sn"), 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 %dn"), GetLastError());
    return 1;
}

作为参考,为了使其与硬编码的文件路径一起工作,我将调用CreateFile()中的"dllPath"参数替换为"TEXT("C:log.log")"。

任何帮助将非常感激!如果这是一个明显的错误,我提前道歉,我仍然试图习惯windows风格的C编程,并且从来没有很好地使用常规风格。

试试这个:

TCHAR dllPath[MAX_PATH+1] = {0}; 
DWORD dllPathLength = 0; 
if(!ReadConsole(hStdIn, dllPath, MAX_PATH, &dllPathLength, NULL)) 
{ 
    _tprintf(TEXT("ReadConsole failed with error %un"), GetLastError()); 
    return 1; 
} 
_tprintf(TEXT("File path entered: %sn"), 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 %un"), GetLastError()); 
    return 1; 
} 

如果仍然不起作用,则确保ReadConsole()在返回路径的末尾不包括换行符或其他终止符,以使其无效。如果是,您必须在调用CreateFile()之前将其剥离。