使用 c++ 从 Linux 中的 Enviornment 变量中查找文件的路径名
Finding Pathname for a file from Enviornment Variable in Linux using c++
所以我正在尝试使用 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 foundn", argv[0]);
return NULL;
}
这里 argv 是参数数组(第 0 个索引包含命令,以下索引包含参数(和 dir[] 包含所有目录的数组
现在我应该如何遍历目录以找到 give 命令的完整路径?
这比我应该提供的要多,但还有足够多的东西你需要弄清楚这不是一个灌篮。
#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++中查找文件
- 在UNIX系统中使用DIR查找文件的字节大小
- 通过搜索硬盘驱动器查找文件目录
- 驱动器号上的查找文件失败,但在路径上传递
- 查找文件中的项目数.txt
- 如何使用c 在Windows中使用更改日记帐查找文件修改
- 如何使用C 在Windows中查找文件是否被修改
- 如何在 c++ 中查找文件指针位置
- 数据文件处理-查找文件中的字数
- 在C 中查找文件的平均薪水
- 比 stat() 在 DIR 中查找文件的更好方法
- C 字符串匹配和使用查找文件替换
- 无法打开或查找文件"afxwin.h",使用.dff(构建毁灭战士3源代码)进行修补
- 如何在不使用目录的情况下在磁盘上查找文件
- 如何避免 CFile查找文件扩展名超过三个字符的误报
- Qt无法在子项目中查找文件
- 查找文件时出现Visual Studio编译错误
- VS2010:设置可执行文件在哪个目录中查找文件
- 使用 C++ 查找文件中的所有重复模式
- 当 seekg 查找文件末尾时未设置故障位 (C++,Linux)