-2

I want to write a script that opens a file in Windows explorer (not just open and read it in cmd, I want it to properly open it like I double clicked it). My first thought was a batch file and it indeed worked, but batch files can be edited and read, and I don't want that. Most batch to .exe converters were marked as viruses so I abandoned the idea and thought of writing a C script and then convert to .exe with codeblocks.

The thing is, I don't know how to open a file in windows explorer from C. Any help would be appreciated!

m.s.
  • 16,063
  • 7
  • 53
  • 88

1 Answers1

3

On windows I suppose you could use system

#include <stdlib.h>

int main(void) {
  system("explorer.exe c:\\path\\to\\file.txt");
  return 0;
}

As discussed in the comments a more robust solution would be to use ShellExecute as in this example.

#include <windows.h>
#include <ShellApi.h>

void view_file(const char* pszFileName) {
  ShellExecute(NULL, NULL, pszFileName, NULL, NULL, SW_SHOW);  
}

int main(void) {
  view_file("c:\\path\\to\\file.txt");
  return 0;
}

If you want to really simulate the default operation when you doubleclick on a file you can pass in NULL as the second parameter

NULL

The default verb is used, if available. If not, the "open" verb is used. If neither verb is available, the system uses the first verb listed in the registry.

Further information about ShellExecute can be read in the docs.

Linus
  • 1,516
  • 17
  • 35
  • You might want to use the full path of `explorer.exe` (e.g "c:\\windows\system32\explorer.exe") – Linus Oct 30 '15 at 16:47
  • I don't think there's any point, if `C:\windows\system32` isn't in your PATH something is seriously wrong. – user4520 Oct 30 '15 at 16:47
  • @szczurcio yeah that was my thought aswell. Unless you have a broken registry it should be fine. – Linus Oct 30 '15 at 16:48
  • Any why not the actual function that is used by Explorer itself to launch the file - [ShellExecute](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762153(v=vs.85).aspx)? – wOxxOm Oct 30 '15 at 16:51
  • 1
    @szczurcio: `windir` and `SystemRoot` not necessarily need to reside on drive C:. – alk Oct 30 '15 at 16:51
  • @alk Of course, I was simplifying, but the point still stands: on a normal system it should be in the PATH. – user4520 Oct 30 '15 at 16:52
  • @wOxxOm Of course `ShellExecute` would be more robust, however since OP seemed to require only a very basic solution I think this will work fine. I'll update my answer though. – Linus Oct 30 '15 at 16:53
  • @Linus, the OP wanted to simulate doubleclick, so instead of `"open"` use `NULL` (and maybe add a note from the docs). Because `open` is not necessarily the default action for a file. – wOxxOm Oct 30 '15 at 17:02