gpt4 book ai didi

c - 解析 $PATH 变量并将目录名称保存到字符串数组中

转载 作者:太空狗 更新时间:2023-10-29 16:05:53 25 4
gpt4 key购买 nike

我想解析Linux的$PATH变量,然后将以':'分隔的目录名保存到一个字符串数组中。

我知道这是一项简单的任务,但我被卡住了,任何帮助都会很好。

到目前为止,我的代码是这样的,但有些地方不对。

char **array;
char *path_string;
char *path_var = getenv("PATH");
int size_of_path_var = strlen(path_var);

path_string = strtok(path_var, ":");
while (path_string != NULL) {
ss = strlen(path_string)
array[i] = (char *)malloc(ss + 1);
array[i] = path_string; //this is actually all i want to do for every path
i++;
path_string = strtok(NULL, ":");
}

最佳答案

您的代码有 2 个主要错误,评论总结了很多:

  • 你 strtok 一个公共(public)缓冲区(由 getenv 返回)
  • 您不知道缓冲区中将有多少变量,因此根本不分配数组的数组!

让我提出一个使用 strtok 的工作实现,从而允许检测空路径(并用 . 替换它,正如 Jonathan 暗示的那样)。使用 gcc -Wall -Wwrite-strings 编译时没有任何警告:

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

int main()
{
const char **array;
const char *orig_path_var = getenv("PATH");
char *path_var = strdup(orig_path_var ? orig_path_var : ""); // just in case PATH is NULL, very unlikely
const char *the_dot = ".";
int j;
int len=strlen(path_var);
int nb_colons=0;
char pathsep = ':';
int current_colon = 0;

// first count how many paths we have, and "split" almost like strtok would do
for (j=0;j<len;j++)
{
if (path_var[j]==pathsep)
{
nb_colons++;
path_var[j] = '\0';
}
}

// allocate the array of strings
array=malloc((nb_colons+1) * sizeof(*array));

array[0] = path_var; // first path

// rest of paths
for (j=0;j<len;j++)
{
if (path_var[j]=='\0')
{
current_colon++;
array[current_colon] = path_var+j+1;
if (array[current_colon][0]=='\0')
{
// special case: add dot if path is empty
array[current_colon] = the_dot;
}

}
}

for (j=0;j<nb_colons+1;j++)
{
printf("Path %d: <%s>\n",j,array[j]);
}

return(0);
}

操作细节:

  • 复制 env 字符串以避免破坏它
  • 计算冒号(为了使其在 Windows 下工作,只需替换为 ;)并标记化
  • 根据冒号数 + 1(比分隔符数多 1 个标记!)分配数组
  • 第二遍再次遍历字符串并用标记化字符串的部分填充它(不需要再次分配,原始字符串已经分配)
  • 特殊情况:空路径:替换为 .。可以显示警告,告诉用户这是不安全的。
  • 打印结果

关于c - 解析 $PATH 变量并将目录名称保存到字符串数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40196067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com