I don’t like WinAPI. That’s why, when I can, I try to find tricks to avoid using it.

Recently during development I had to convert a given Windows short filename (or, more formally, a 8.3 filename) to a long one. In order to avoid calling WinAPI’s conversion “GetLongPathNameA”, I found this little detour around it using C++17 “filesystem::canonical” instead.

#include <filesystem>
#include <iostream>
#include <string>
#include <format> // C++20 Required

namespace fs = std::filesystem;

std::string to_long_path(const std::string& short_path) {
    return fs::canonical(short_path).string();
}

int main() {
    std::string short_path{"C:\\PROGRA~1"};
    auto long_path = to_long_path(short_path);
    std::cout << std::format(R"(Short Path: "{}". Long Path Using std::fs: "{}")", short_path, long_path);
    // Output: Short Path: "C:\PROGRA~1". Long Path Using std::fs: "C:\Program Files"
}

Hooray! No need for “GetLongPathNameA” 🙌

What do you think? Do you share my approach as well?

The full snippet can be found here: Github Gist.