【问题标题】:How to open a file relative to the executables location in C?如何在 C 中打开相对于可执行文件位置的文件?
【发布时间】:2019-12-22 19:31:51
【问题描述】:

假设编译后的 C 二进制文件位于 ~/bin/my_cool_c_program.out,我有以下代码:

FILE *file = fopen("helloworld.txt");
perror("Open helloworld.txt");

现在我面临一个问题,代码在我执行二进制文件的目录中创建helloworld.txt 文件,而不是相对于二进制文件所在的位置。所以从~ 调用它会创建~/helloworld.txt,但我希望它保存到~/bin/helloworld.txt。我尝试用"./helloworld" 替换它,但这也不起作用。当我从~/bin/ 目录本身调用时,一切都按预期工作。

为什么在创建文件后第一个结果是perror 打印Permission denied,而第二个结果是Successful


注意:我会检查 file == NULL 等等。为了简单起见,我只是将其删除。

【问题讨论】:

  • 你可能会找到一些帮助here
  • 没想到,这个没有标准????
  • 在 fopen 调用中缺少表示打开模式的第二个参数。

标签: c file permissions


【解决方案1】:

没有可移植的方法来做到这一点。 如果argv[0]所指向的字符串(argvmain函数的第二个参数,虽然可以使用任何其他名称),代表程序名称,包含程序的路径(没有这样的保证) ,那么就可以使用下面的代码了:

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

/* filename separator (depends on the operating system) */
#define SEP '/'

int main (int argc, char *argv[])
{
        FILE *fp;
        const char *filename = "helloworld.txt";
        const char *lastslash;
        if (argc > 0 && (lastslash = strrchr(argv[0], SEP)) != NULL) {
                const int len = lastslash - argv[0] + 1;
                char *const pathname = malloc(len + strlen(filename) + 1);
                if (pathname == NULL) {
                        perror("malloc");
                        return EXIT_FAILURE;
                }
                sprintf(pathname, "%.*s%s", len, argv[0], filename);
                fp = fopen(pathname, "w");
                free(pathname);
                if (fp == NULL) {
                        perror("fopen");
                        return EXIT_FAILURE;
                }
        } else {
                fputs("No path information in argv[0]\n", stderr);
                return EXIT_FAILURE;
        }

        return 0;
}

【讨论】:

  • 谢谢!我会查看你的代码,但我会使用this library
  • 如果 argv[0] 以“/”(绝对路径)开头,这就是路径。否则,如果 argv[0] 包含“/”(相对路径),则将其附加到 cwd(假设尚未更改)。否则在 $PATH 中搜索可执行 argv[0] 的目录。来自this 的回答。在$PATH 中寻找程序将使其大部分时间都能正常工作
猜你喜欢
  • 2012-02-26
  • 2021-09-03
  • 2011-06-19
  • 2011-11-02
  • 2016-04-19
  • 1970-01-01
  • 1970-01-01
  • 2014-05-03
  • 1970-01-01
相关资源
最近更新 更多