[英]How do I open a file in its default program - Linux
How do I programmatically open a file in its default program in Linux (im using Ubuntu 10.10).如何以编程方式在 Linux 的默认程序中打开文件(我使用 Ubuntu 10.10)。
For example, opening *.mp3 will open the file in Movie Player (or something else).例如,打开 *.mp3 将在 Movie Player(或其他)中打开文件。
You need to run gnome-open, kde-open, or exo-open, depending on which desktop you are using.您需要运行gnome-open、kde-open 或 exo-open,具体取决于您使用的桌面。
I believe there is a project called xdg-utils that attempts to provide a unified interface to the local desktop.我相信有一个名为xdg-utils的项目试图为本地桌面提供统一的界面。
So, something like:所以,像:
snprintf(s, sizeof s, "%s %s", "xdg-open", the_file);
system(s);
Beware of code injection.谨防代码注入。 It's safer to bypass scripting 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
Ubuntu 10.10 is based on GNOME. Ubuntu 10.10 基于 GNOME。 So, it would be good idea to use g_app_info_launch_default_for_uri()
.因此,使用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 determin your desktop environment and call a known helper like gvfs-open
for GNOME, kde-open
for KDE, or something else.顺便说一句, xdg-open
是一个 shell 脚本,它会尝试确定您的桌面环境并调用已知的帮助程序,例如 GNOME 的gvfs-open
、KDE kde-open
或其他。 gvfs-open
ends up calling g_app_info_launch_default_for_uri()
. gvfs-open
最终调用g_app_info_launch_default_for_uri()
。
A simple solution with less coding:一个编码较少的简单解决方案:
I've tested this program on my Ubuntu and it is working fine, and if I am not wrong you are looking for something like this我已经在我的 Ubuntu 上测试了这个程序,它工作正常,如果我没有错,你正在寻找这样的东西
#include <stdio.h>
#include <stdlib.h>
int main()
{
system("firefox file:///dox/song.mp3");
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.