2011-05-26 104 views
3

如何以编程方式在Linux的默认程序中打开文件(即时消息使用Ubuntu 10.10)。如何在其默认程序中打开文件 - Linux

例如,打开* .mp3将在Movie Player(或其他)中打开该文件。

预先感谢您。

斯捷潘

+0

Ubuntu默认配备了firefox,如果你可以从你的终端运行'firefox'命令....你可以正确....看看我的解决方案....看看这是否工作对你来说 – 2014-02-15 20:05:34

回答

5

您需要侏儒开,KDE开或外开,这取决于你所使用的桌面运行。

我相信有一个项目叫做xdg-utils,它试图为本地桌面提供一个统一的接口。

所以,像这样:

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

谨防代码注入的。使用用户输入绕过脚本层更安全,因此请考虑如下内容:

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 
+2

'xdg-open'会调用适当的一个。 – ninjalj 2011-05-26 18:12:38

+0

@ninjalj,非常好,我希望pkg能够做到这一点。我认为这是Chrome使用的。 – DigitalRoss 2011-05-26 18:14:32

+0

虽然我建议使用'execv *'而不是'system'。 – ninjalj 2011-05-26 18:15:14

2

Ubuntu 10.10基于GNOME。所以,最好使用 g_app_info_launch_default_for_uri()

这样的事情应该工作。

#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,一个shell脚本,试图determin您的桌面环境,并调用一个已知的帮手像gvfs-open为GNOME,kde-open对于KDE,或别的东西。 gvfs-open最终致电g_app_info_launch_default_for_uri()

+0

如果应用程序已经依赖于GNOME,我更喜欢这种方法。 – Serrano 2013-10-02 10:19:52

0

用更少的编码简单的解决方案:

我测试过在我的Ubuntu这个程序,它工作正常,如果我没看错你正在寻找这样的事情


#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
    system("firefox file:///dox/song.mp3"); 
    return 0; 
} 
相关问题