问题描述
|
我如何以编程方式在Linux的默认程序中打开文件(例如,使用Ubuntu 10.10)。
例如,打开* .mp3将在Movie Player中打开文件(或其他)。
解决方法
您需要运行gnome-open,kde-open或exo-open,具体取决于您使用的桌面。
我相信有一个名为xdg-utils的项目,试图为本地桌面提供统一的接口。
因此,类似:
snprintf(s,sizeof s,\"%s %s\",\"xdg-open\",the_file);
system(s);
当心代码注入。通过用户输入绕过脚本层较为安全,因此请考虑以下内容:
pid = fork();
if (pid == 0) {
execl(\"/usr/bin/xdg-open\",the_file,(char *)0);
exit(1);
}
// parent will usually wait for child here
,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脚本,它试图确定您的桌面环境,并调用一个已知的帮助程序,例如GNOME的gvfs-open
,KDE的kde-open
或其他。 gvfs-open
最终呼叫g_app_info_launch_default_for_uri()
。
,编码少的简单解决方案:
我已经在Ubuntu上测试了该程序,并且运行良好,如果我没记错,您正在寻找类似的东西
#include <stdio.h>
#include <stdlib.h>
int main()
{
system(\"firefox file:///dox/song.mp3\");
return 0;
}