C++ - What is \\?\ ?

The string \\?\ (backslash backslash question-mark backslash) is a prefix that can be added to a path name, and used in Windows API calls, to instruct Windows to bypass the MAX_PATH (256 char) path length limitation.

The example below is a C++ console application compiled for Unicode. It attempts to create a directory longer than MAX_PATH characters.

If you set usePrefix to true, the path is prefixed with \\?\, and the call to CreateDirectory will succeed, otherwise it will fail with error 206 — The filename or extension is too long.

#include "stdafx.h"
#include <windows.h>
 
int main()
{
    // This is our base directory.
    // len = 245
    const wchar_t* path = L"C:\\temp\\a very long path\\a very long path\\a very long path\\a very long path\\a very long path\\a very long path\\a very long path\\a very long path\\a very long path\\a very long path\\a very long path\\a very long path\\a very long path\\a very long path";
 
    //
    // Prepend \\?\ to the absolute path of the directory.
    // This will not work with a relative path. It must be a full path.
    //
    wchar_t szFullPath[1024] = L"";
    bool usePrefix = true;
    if (usePrefix)
    {
        lstrcat(szFullPath, L"\\\\?\\");
    }
    lstrcat(szFullPath, path);
    lstrcat(szFullPath, L"\\new-subdir");
 
    BOOL ret = ::CreateDirectory(szFullPath, NULL);
    DWORD error = ret ? 0 : ::GetLastError();
 
    //
    // If usePrefix is false, ret = false, and error=206. The filename or extension is too long.
    //
    // If usePrefix is true, ret = true
    //
    // (If you are running the program for the 2nd time, and the directory already exists, you will see error 183.
    // Cannot create a file when that file already exists.)
    //
 
    return 0;
}
 

Ads by Google


Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath