gpt4 book ai didi

c++ - 环境变量拆分为名称和值 c

转载 作者:太空宇宙 更新时间:2023-11-04 04:49:44 24 4
gpt4 key购买 nike

我正在尝试解析 envp 数组以获取程序变量的名称和值(稍后会用到),但我想我在 realloc 方面不够好,有人可以帮助我吗?

void envset(char *envp[]) {
char *name = NULL;
char *value = NULL;
char *temp = NULL;
char *tok;
int i = 0;

while (envp[i] != 0) {
printf("envp[%d] = %s", envp[i]);
temp = realloc(temp, sizeof(envp[i]));
strcpy(temp, envp[i]);
tok = strtok(temp, "=");
while (tok!=NULL){
name = realloc(name, sizeof(tok));
strcpy(name, tok);
tok = strtok(NULL, "=");
value = realloc(value, sizeof(tok));
strcpy(value, tok);
printf("Name = %s, value = %s", name, value);
}
change_var(name, value);
i++;
}
}

最佳答案

我可以建议一种不同的、更标准的打印方式吗?

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

extern char **environ; /* this is an external variable provided by the environment */

int main()
{
char** env_ptr; /* declare a char** pointer that we will use to iterate through 'environ' */

char* ptr = 0; /* this is used as a helper variable to store what 'strtok' returns */

/* while the current string pointed to by *env_variable is not empty, increment it. */
for (env_ptr = environ; *env_ptr != NULL; env_ptr++)
{
int i = 0; /* this is a control variable that is used to separate the left from the right part (divided by '=') */

char temp[255] = ""; /* temporary string that will hold the whole current environment variable */

strcpy(temp, *env_ptr);

ptr = strtok(temp, "="); /* we specify the delimiters here, 'ptr' first points to the left part */

char temp_a[255]; /* these two strings will hold the left and the right part respectively*/
char temp_b[255];

while (ptr != NULL)
{
if (i == 0) /* in the first iteration we get the left part so we store it */
strcpy(temp_a, ptr);

if (i == 1) /* in the second iteration we get the right part so we store it */
strcpy(temp_b, ptr);

ptr = strtok(NULL, "="); /* set 'ptr' to point to the right part,
if this is already the second iteration,
it will point to NULL */

i++;
}

printf("%s - %s\n", temp_a, temp_b); /* you can assign temp_a and temp_b to anything you like */

}

return 0;
}

编辑:代码已更新,我没有您严格的详细信息,但您可以将 temp_atemp_b 分配给其成员字段

输出如下:

$ ./a.out 
LC_PAPER - en_US.UTF-8
LC_ADDRESS - en_US.UTF-8
SSH_AGENT_PID - 1311
LC_MONETARY - en_US.UTF-8
GPG_AGENT_INFO - /tmp/keyring-YUiDNO/gpg:0:1
TERM - xterm
SHELL - /bin/bash

关于c++ - 环境变量拆分为名称和值 c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16873778/

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