Home > Software engineering >  CreateFileW with \\?\ prefix and long file name returned INVALID_HANDLE_VALUE
CreateFileW with \\?\ prefix and long file name returned INVALID_HANDLE_VALUE

Time:01-07

#include <Windows.h>
#include <cassert>

int main()
{
    auto h = CreateFileW(
        LR"(\\?\C:\Looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooog.txt)",
        GENERIC_READ | GENERIC_WRITE,
        0,
        nullptr,
        CREATE_NEW,
        FILE_ATTRIBUTE_NORMAL,
        NULL
    );
    assert(h != INVALID_HANDLE_VALUE);
    CloseHandle(h);
}

enter image description here

What am I doing wrong here?

Project settings btw: enter image description here

Running with admin doesn't solve the issue either. I am running windows 11 22621 enter image description here

CodePudding user response:

You are running into an NTFS (presumably) limitation, where path components (including the file name) are limited to 255 UTF-16 code units. The file name you are supplying is 263 code units long, and you are getting an ERROR_INVALID_NAME error code ("The filename, directory name, or volume label syntax is incorrect.").

To solve this, you'll need to make the file name part no longer than 255 UTF-16 code units.

CodePudding user response:

You wrote incorrect escape sequence. Try this:

#include <Windows.h>
#include <cassert>

int main()
{
    auto h = CreateFileW(
        LR"(\\\\?\\C:\\Looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooog.txt)",
        GENERIC_READ | GENERIC_WRITE,
        0,
        nullptr,
        CREATE_NEW,
        FILE_ATTRIBUTE_NORMAL,
        NULL
    );
    assert(h != INVALID_HANDLE_VALUE);
    CloseHandle(h);
}
  • Related