c++ - 使用 C++ 从 Linux 环境变量中查找文件的路径名

标签 c++ c linux environment-variables

所以我尝试使用 C/C++ 在 Ubuntu 中创建命令行解释器 这是我们大学实验室任务的一部分 CLI 的基本功能是从用户处获取输入,解析它以查找命令及其参数,然后从环境变量中查找命令的路径名
我已经能够解析字符串,获取命令及其参数,我还能够读取路径环境变量以获取所有路径的目录。现在我必须浏览这些目录以找到文件(命令)所在的位置,然后返回完整路径,以便可以将其发送到 execve 以在子进程中执行 我必须创建一个查找函数,它接受参数数组(第 0 个索引位置包含命令名称)和目录数组 这是提供给我们的功能概要

// Search the directories identified by the dir argument to see
// if the argv[0] (the filename) appears there. Allocate a new
// string, place the full path name in it, then return the string.
//
char* lookupPath(char **argv, char **dir){
char* result;
char pName[MAX_PATH_LEN];
// check if is already an absolute path name
if( *argv[0] == '/' ) .....
// look in PATH directories, use access() to see if the
// file is in the dir
for( i = 0 ; i < MAX_PATHS ; i++ ) .....
// File name not found in any path variable
fprintf(stderr, "%s: command not found\n", argv[0]);
return NULL;
}

这里argv是参数数组(第0个索引包含命令,后面的索引包含参数) dir[] 包含所有目录的数组

现在我想如何遍历目录来找到给定命令的完整路径?

最佳答案

这超出了我应该提供的范围,但你还需要弄清楚这不是一个灌篮。

#include <unistd.h>

typedef std::vector<std::string> pathArray;

std::string lookupPath(const std::string pgm, pathArray &paths)
{
    int ret;

    for (int i = 0; i < paths.size(); ++i)
    {
       std::string temp = paths[i];

       temp = temp + "/" + pgm;

       // let execv determine if it is executable
       // or you can do that here if required
       if ((ret = access(temp.c_str(), F_OK)) == 0) 
           return temp;
    }

    return("");
}

int main(int argc, char *argv[])
{
    pathArray pa;

    pa.push_back("/bin");
    pa.push_back("/usr/bin"); //and the rest of PATH contents

    std::string pgm;
    std::string fullpath;

    pgm = "ls";

    if ((fullpath = lookupPath(pgm, pa)) != "")
    {
        //execv(fullpath.c_str(), ....);
        //etc...
    }
    else
    {  //could not find pgm
    }

    return(0);
}

关于c++ - 使用 C++ 从 Linux 环境变量中查找文件的路径名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19079536/

相关文章:

c++ - 有没有办法在编译时测试类型是否为 "bool operator==(const type&, const type&)"?

c++ - 为什么要重新抛出异常

c++ - 有没有办法继承迭代器的东西

Linux fifo(命名管道)O_NONBLOCK 中断管道

C++ 简单字典 : list of sorted words

将 uint16_t 转换为十进制并将其按位存储在 char 数组中。检索 uint16_t 变量中的数据时出错

c - C 中随机名称按字母顺序排序

c - 为什么 _SC_AIO_MAX 定义明确,而 sysconf(_SC_AIO_MAX) 返回 -1?

linux - ssh inside ssh 具有多个命令

linux - 无法通过 asdf 使用 openssl 安装 Erlang (Ubuntu 18.04.1)