C++(Unix):使用默认编辑器打开文本文件

7
问题如上所述,我在谷歌上的搜索没有成功。 我想我需要获取默认编辑器,然后使用 system("editor file.txt");? 如何获取默认编辑器?
编辑:我不知道为什么,但stackoverflow不喜欢我的“嘿”,那就算了。

1
可能是从bash中打开默认编辑器的文件的重复问题。 - Frédéric Hamidi
@FrédéricHamidi 对不起,但我不能同意。那不是 C++,而且有人可以给我一个替代 system() 的方法。 - Vider7CC
好的,我只是想指出xdg-open给你。 - Frédéric Hamidi
@FrédéricHamidi 好的,谢谢。使用xdg-open而不是bin/sensible-editor(pts的答案)有什么缺点吗? - Vider7CC
xdg-open 是 freedesktop.org 的工具,sensible-editor 是 Debian 的工具... 我猜这取决于您想要支持的平台。 - Frédéric Hamidi
确实,解决方案的复杂性取决于您打算支持哪些操作系统。您还应该意识到,使用通用编辑器可能会引入一个巨大的安全漏洞。 - Component 10
2个回答

9

目前没有官方的解决方案。以下是我推荐的打开文本编辑器的方法:

如果文件名后缀是.txt,并且xdg-open$PATH上可用且$DISPLAY变量非空,则使用xdg-open。否则,如果存在,则使用/usr/bin/sensible-editor。否则,使用getenv("EDITOR")getenv("VISUAL")getenv("SELECTED_EDITOR")。如果都没有设置,则尝试使用nanonano-tiny,最后使用vi


1
值得补充的是:xdg-open并不是"C++的官方部分",但它是"最广泛?"遵循的Linux桌面标准的一部分:https://freedesktop.org/wiki/ - Ciro Santilli OurBigBook.com

4

有一个例子可以获取默认的编辑器环境,从visudo(它使用默认编辑器来打开sudoers文件)的源代码中:

/*
     * Check EDITOR and VISUAL environment variables to see which editor
     * the user wants to use (we may not end up using it though).
     * If the path is not fully-qualified, make it so and check that
     * the specified executable actually exists.
     */
    if ((UserEditor = getenv("EDITOR")) == NULL || *UserEditor == '\0')
    UserEditor = getenv("VISUAL");
    if (UserEditor && *UserEditor == '\0')
    UserEditor = NULL;
    else if (UserEditor) {
    if (find_path(UserEditor, &Editor, getenv("PATH")) == FOUND) {
        UserEditor = Editor;
    } else {
        if (def_flag(I_ENV_EDITOR)) {
        /* If we are honoring $EDITOR this is a fatal error. */
        (void) fprintf(stderr,
            "%s: specified editor (%s) doesn't exist!\n",
            Argv[0], UserEditor);
        Exit(-1);
        } else {
        /* Otherwise, just ignore $EDITOR. */
        UserEditor = NULL;
        }
    }
    }

你可以查看http://www.opensource.apple.com/source/sudo/sudo-9/sudo/visudo.c获取完整代码。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接