使用Win32 API读取用户指定的文件
Reading a user-specified file with the Win32 API
我试图提示用户在控制台输入文件名/路径,然后尝试使用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()
之前将其剥离。
相关文章:
- 以非特权用户身份查询 NTFS 特殊文件的元数据?
- 用户输入字符串的文件附加问题..C++
- MAKE:找不到包含的用户定义的头文件?
- 从标准输入读取文件后读取用户输入
- 限制用户可以在 QFileDialog 中选择的文件数量
- 如何在公共头文件中向库的用户公开枚举,同时在内部使用它?
- Windows 后台服务(系统配置文件)无法使用 C++ 访问 win 10 上的用户 appData 文件夹?
- 如何让用户在 tinyxml2 中输入 XML 文件的路径
- Arduino-Makefile:编译器无法编译用户库 cpp 文件
- 将所有 *.txt 文件合并到一个文本文件中,其名称由用户使用 C++ 提供
- 如何在 c++ 中将密码和用户名保存到 .txt 文件中.如果用户尝试登录,我仍然希望能够检索它们
- 尝试将文本文件中的整数替换为用户输入的整数 [C++]
- 尝试读取.txt文件并根据用户输入的字母拉出特定行
- Win7 C++ - 从以用户身份登录的服务启动可执行文件的问题
- 可以将Boost消息队列文件重定向到用户指定的位置
- 在 Win32 应用中,如果未选择文件夹并且用户单击"确定",则文件夹选择对话框将关闭
- 是否可以用类似C/C++(或任何语言)的语言,从作为用户输入的字符串或文件中创建用户定义的数据类型
- 读取用户必须提供一些参数的文件
- g++ 生成依赖项文件缺少用户定义的标头
- 用户使用C++中的删除功能删除文件