Linux中的"获取"路径

时间:2020-03-05 18:48:35  来源:igfitidea点击:

我正在用linux编写一个c程序。像execv()这样的命令需要c字符串形式的路径。是否有一条命令将以c样式字符串的形式返回当前路径?

解决方案

回答

getcwd():

SYNOPSIS

#include <unistd.h>

char *getcwd(char *buf, size_t size);

  
  DESCRIPTION
  
  The getcwd() function shall place an absolute pathname of the current working directory in the array pointed to by buf, and return buf. The pathname copied to the array shall contain no components that are symbolic links. The size argument is the size in bytes of the character array pointed to by the buf argument. If buf is a null pointer, the behavior of getcwd() is unspecified.
  
  RETURN VALUE
  
  Upon successful completion, getcwd() shall return the buf argument. Otherwise, getcwd() shall return a null pointer and set errno to indicate the error. The contents of the array pointed to by buf are then undefined....

回答

我不是专业的程序员,所以这不是确切的答案。

我们需要做的是获取环境变量PWD(当前工作目录)

我不确定它在哪个库中,但是它是一个标准的linux头文件。

我会环顾四周,看看是否可以找到它。

编辑:

我在想,getenv(),如果我们还需要运行系统命令并且需要位于PATH中的各种bin路径,这将有所帮助

回答

这不是ANSI C:

#include <unistd.h>

char path[MAXPATHLEN];
getcwd(path, MAXPATHLEN);
printf("pwd -> %s\n", path);

回答

execv()的path参数是我们要执行的应用程序的路径,而不是当前的工作目录(将由getcwd()返回)或者外壳程序搜索路径(将由getenv(" PATH")返回) )。

根据工作,我们可能会从C库的system()函数中获得更多收益,而不是从较低级别的exec()系列中获得更多收益。

回答

如果该路径可以是相对路径,则应该可以使用"。"。或者以" ./"作为路径。我不确定它是否会起作用,但是我们可以尝试一下。