Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find target of symbolic link in Windows C++ program

Tags:

c++

winapi

I am developing an application with Visual Studio C++ 2008 and 2010. I have a simple need: I want to find out the target of a symbolic link (.lnk or shortcut) file. I have combed the web to find the answer and haven't had any luck.

I can see MSDN has two function to create symbolic links

BOOLEAN WINAPI CreateSymbolicLink( In LPTSTR lpSymlinkFileName, In LPTSTR lpTargetFileName, In DWORD dwFlags );

BOOLEAN WINAPI CreateSymbolicLinkTransacted( In LPTSTR lpSymlinkFileName, In LPTSTR lpTargetFileName, In DWORD dwFlags, In HANDLE hTransaction );

but I see nothing that let's you retrieve the target path. This seems weird to me as it is such a basic property of a symbolic link file. Wouldn't that information be kept in the file header info?

One suggestion as recommended on MSDN site was this

h = CreateFile (
        path,
        FILE_READ_ATTRIBUTES,
        FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
        0,
        OPEN_EXISTING,
        FILE_FLAG_BACKUP_SEMANTICS | FILE_ATTRIBUTE_REPARSE_POINT | FILE_FLAG_OPEN_REPARSE_POINT,
        0);

DeviceIoControl (
        h,
        FSCTL_GET_REPARSE_POINT,  
        NULL,
        0,
        buffer,
        bufferSize,
        &returnedDataSize,
        NULL);

But it doesn't look like DeviceIoControl makes sense for symbolic links anyway since it's a device control function. I tried it anyway and it didn't work, that is buffer was unchanged.

Does anyone out there have any experience with this? Any help would be greatly appreciated.

Jay

like image 555
user3630595 Avatar asked Oct 27 '25 07:10

user3630595


2 Answers

A .lnk file is not a symbolic link. Symbolic links are a feature of the file system itself. That is why you can use DeviceIoControl() to query them. A .lnk file is just that - a file. You use the IShellLink interface to query and manipulate .lnk files.

like image 152
Remy Lebeau Avatar answered Oct 29 '25 22:10

Remy Lebeau


Have you tried opening the symbolic link with the CreateFile() API? Specifically, this is what the doc for the API says about opening symbolic links:

If FILE_FLAG_OPEN_REPARSE_POINT is not specified:

  • If an existing file is opened and it is a symbolic link, the handle returned is a handle to the target.
  • If CREATE_ALWAYS, TRUNCATE_EXISTING, or FILE_FLAG_DELETE_ON_CLOSE are specified, the file affected is the target.

So, you can try opening the link, which would return the handle to the target file, and then try to retrieve the filename from the returned handle as per Obtaining a File Name From a File Handle.

I have never tried it, but just an approach that you can consider exploring.

like image 28
Hari Mahadevan Avatar answered Oct 29 '25 22:10

Hari Mahadevan



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!