Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replacement for readlink() function in windows

readLink() is present in linux and is defined in unistd.h,is there any similar type function in windows please provide or else if we can make a function with similar functionality.I want to use the same functionality as readLink() please provide a user defined function for the replacement of the function in case no predefined function is there provided snap of the code

        char buffer[2048];

        readlink("/proc/self/exe", buffer, 2048);

        std::stringstream ss;
        ss << buffer;
        std::string exeFile = ss.str();
        std::string directory;

        const size_t last_slash_idx = exeFile.rfind('/');
        if (std::string::npos != last_slash_idx)
        {
            directory = exeFile.substr(0, last_slash_idx);
        }
        return directory;
    #endif 
like image 320
Ankit Srivastava Avatar asked Jul 11 '26 13:07

Ankit Srivastava


1 Answers

Windows doesn't have a readlink(2) equivalent, but it does have a realpath(3) equivalent: GetFinalPathNameByHandleW().

See also: "How do I get information about the target of a symbolic link?" by Ramond Chen.

Pseudo-code is as follows, error checking omitted:

HANDLE hPath = CreateFileW(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
DWORD len = GetFinalPathNameByHandleW(hPath, NULL, 0, FILE_NAME_OPENED);
WCHAR* realPathBuf = new WCHAR[len+1];
GetFinalPathNameByHandleW(hPath, realPathBuf, len, FILE_NAME_OPENED);

Note that realPathBuf may be a "local UNC" path, starting with \\?\.

like image 186
jonp Avatar answered Jul 13 '26 06:07

jonp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!