我正在尝试使用用户输入的路径创建一个具有 GENERIC_WRITE 权限的文件。
为了获取用户输入,我使用
fwgets
函数。
VOID DoCreateFile() {
SIZE_T sAlloc = sizeof(WCHAR) * (MAX_WPATH + 1); // allocation size
// allocating space and checking if actually allocated
LPWSTR lpPath = (LPWSTR)malloc(sAlloc);
LPWSTR lpContent = (LPWSTR)malloc(sAlloc);
if (lpPath == NULL || lpContent == NULL) {
PrintLastError(L"malloc()", TRUE);
}
wprintf(L"Enter path of file: ");
fgetws(lpPath, sAlloc, stdin); // read the contents of stdin with space
wprintf(L"Enter content (max 256 chars): ");
fgetws(lpContent, sAlloc, stdin);
/*
Documentation: https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew
*/
HANDLE hFile = CreateFileW(lpPath, // path of file
GENERIC_WRITE, // creating file with write permission
FILE_SHARE_READ, // allow other process to open file for reading
NULL, // disallow handle inheritance
CREATE_ALWAYS, // overwrite file if exists, otherwise create a new one
FILE_ATTRIBUTE_NORMAL, // do not set any file attributes
NULL // not using any file template
);
if (hFile == INVALID_HANDLE_VALUE) {
PrintLastError(L"CreateFileW()", TRUE);
}
CloseHandle(hFile);
}
PrintLastError 函数打印的错误消息: CreateFileW() 失败!文件名、目录名或卷标语法不正确。
我在控制台输入的输入是
Enter path of file: c:\file.txt
Enter content (max 256 chars): s
我也尝试过文件路径
\\.\C:\file.txt
。
仅供参考,当我用宽字符串文字
lpPath
替换 L"C:\\Files.txt"
时,函数成功。