由于路径无效,CreateFileW 失败

时间:2021-07-11 13:00:07

标签: c windows winapi

我正在尝试使用用户输入的路径创建一个具有 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://docs.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" 时,函数成功。

0 个答案:

没有答案