How to open a file in your program by default - Linux

How to programmatically open a file in your default program on Linux (im using Ubuntu 10.10).

For example, the opening of * .mp3 file will open in Movie Player (or something else).

Thanks in advance.

Stepan

+4
source share
3 answers

You need to run gnome-open, kde-open or exo-open, depending on which desktop you are using.

I believe there is a project called xdg-utils that is trying to provide a unified interface to the local desktop.

So something like:

snprintf(s, sizeof s, "%s %s", "xdg-open", the_file); system(s); 

Beware of code injection. It is safer to bypass script layers with user input, so consider something like:

 pid = fork(); if (pid == 0) { execl("/usr/bin/xdg-open", "xdg-open", the_file, (char *)0); exit(1); } // parent will usually wait for child here 
+5
source

Ubuntu 10.10 is based on GNOME. Thus, it would be nice to use g_app_info_launch_default_for_uri() .

Something like this should work.

 #include <stdio.h> #include <gio/gio.h> int main(int argc, char *argv[]) { gboolean ret; GError *error = NULL; g_type_init(); ret = g_app_info_launch_default_for_uri("file:///etc/passwd", NULL, &error); if (ret) g_message("worked"); else g_message("nop: %s", error->message); return 0; } 

BTW, xdg-open , a shell script, tries to determine the desktop environment and call a well-known helper, such as gvfs-open for GNOME, kde-open for KDE, or something else. gvfs-open ends with a call to g_app_info_launch_default_for_uri() .

+2
source

Simple solution with less coding:

I tested this program on my Ubuntu and it works fine, and if I'm not mistaken, you are looking for something like this


 #include <stdio.h> #include <stdlib.h> int main() { system("firefox file:///dox/song.mp3"); return 0; } 
0
source

All Articles