在环境变量中查找一个元素,如果存在的话,将它的值分别打印出来
1 /*
2 * Look up a given string in the environment variable,
3 * print out its values respectively if present.
4 *
5 * viechang@gmail.com
6 */
7
8 #include <stdlib.h>
9 #include <string.h>
10 #include <stdio.h>
11
12 #include <iostream>
13
14 using namespace std;
15
16 #define ENV_MAX_CHAR 0x0400
17
18 int
19 main(int argc,
20 char *argv[],
21 char **env)
22 {
23 int cnt = 0;
24
25 if (argc < 2) {
26 cout << "Usage: a.out <string> " << endl;
27 return EXIT_FAILURE;
28 }
29
30 for (cnt = 0; env[cnt] != NULL; cnt++) {
31 if (0 == strnicmp(env[cnt], argv[1], 4)) {
32 char *p = (char *)malloc(ENV_MAX_CHAR * sizeof(char));
33 char *pch = NULL;
34
35 strcpy(p, env[cnt]);
36 cout << "#Splitting string: " << endl;
37 cout << "\"" << p << "\"" << endl;
38 cout << "#into tokens:\n" << endl;
39
40 pch = strtok(p, "=;");
41 while(pch != NULL) {
42 cout << pch << endl;
43 pch = strtok(NULL, "=;");
44 }
45
46 free(p);
47 break;
48 }
49 }
50 if (env[cnt] == NULL)
51 cout << "Nothing match.";
52
53 return EXIT_SUCCESS;
54 }
2 * Look up a given string in the environment variable,
3 * print out its values respectively if present.
4 *
5 * viechang@gmail.com
6 */
7
8 #include <stdlib.h>
9 #include <string.h>
10 #include <stdio.h>
11
12 #include <iostream>
13
14 using namespace std;
15
16 #define ENV_MAX_CHAR 0x0400
17
18 int
19 main(int argc,
20 char *argv[],
21 char **env)
22 {
23 int cnt = 0;
24
25 if (argc < 2) {
26 cout << "Usage: a.out <string> " << endl;
27 return EXIT_FAILURE;
28 }
29
30 for (cnt = 0; env[cnt] != NULL; cnt++) {
31 if (0 == strnicmp(env[cnt], argv[1], 4)) {
32 char *p = (char *)malloc(ENV_MAX_CHAR * sizeof(char));
33 char *pch = NULL;
34
35 strcpy(p, env[cnt]);
36 cout << "#Splitting string: " << endl;
37 cout << "\"" << p << "\"" << endl;
38 cout << "#into tokens:\n" << endl;
39
40 pch = strtok(p, "=;");
41 while(pch != NULL) {
42 cout << pch << endl;
43 pch = strtok(NULL, "=;");
44 }
45
46 free(p);
47 break;
48 }
49 }
50 if (env[cnt] == NULL)
51 cout << "Nothing match.";
52
53 return EXIT_SUCCESS;
54 }