我可以建议一种不同的、更标准的打印方式吗?
#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_a
给temp_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