Is there a universal way to open a location in the default file explorer in C?

Viewed 136

I am writing a C program that needs to open a location in the default file explorer (e.g. open C:\Program Files (x86)\somefolder in the Windows file explorer, or open /usr/share/somefolder in Nautilus/Nemo/whatever default file explorer program is set).

Is there an universal way to do that, as in a way that uses the same code for both Windows and Linux?

I did find this question that uses ShellExecute(), but this probably doesn't work on Linux. So, is it possible, and if not, is there a way to separate the code for Linux and Windows?

1 Answers

This is not possible in pure C. In fact, the C standard does not mention "Linux" or "Windows" at all. Even the words "operating system" only occur twice. The first occurrence is in 5.1.2.1-1:

In a freestanding environment (in which C program execution may take place without any benefit of an operating system) [...]

The alternative to a freestanding environment is a hosted environment (5.1.2-1). The standard continues to use the term "hosted environment", but does not distinguish between different operating systems.

A common solution is to use preprocessor macros to conditionally compile code depending on the target operating system. E.g.:

#ifdef __linux__ 
    // Open in Linux. E.g. // system("xdg-open ...");
#elif __CYGWIN__
    // Open in Windows.
#else
#error "Error: OS not supported."
#endif

This question contains a list of operating systems and corresponding macros.

Related