The technique of using environment variables in C language

Source: Internet
Author: User
Tags define variables printf

Example 1:

Program READENV.C shows several techniques for accessing environment variables in C language. The program prints out all the current environment variables in the same format as the DOS SET command, then looks for the path variable and prints out the entire path string. There are two important subroutines in the program, Find_env_string (), whose main function is to look for the next first environment string, depending on the request from the call, or from the beginning of the environment space, or from the place where the last search has been made, and the following list of specific procedures.

/**************readnv.c****************/

#include
#include
#include
#define max 127
#define true 1
#define false 0
#define first 1
#define next 0
void dispenv(void);
int find_env_string(int restart);
char env_string[max+2];
int env_offset=0;
void main()
{
char *path_string; /*调用子程序dispenv(),以与set命令相同的格式打印出当前环境字符串*/
dispenv(); /*在环境变量中寻找path变量,并打印出整个论经字符串*/
if(path_string==getenv("path"))
printf("\nPATH=%s",path_string);
}

/********************************************/

void dispenv()
{
int restart; /*在for循环中,先置restart为first,调用子程序find_env_string()
寻找第一个环境字符串并打印,而后置restart为next,继续寻找下一
个环境字符串,直到结束子程序find_env_string()返回false为止*/
for(restart=first;find_env_string(restart);restart=next)
printf("\n%s",env_string);
}
/********************************************/
int find_env_string(int restart)
{
int buf_offset;
int environment;
if(!environment) /*将环境空间短地址送入变量environment中*/
environment=peek(_psp,0x2c);
if(restart)
environment=0; /*首次调用时,偏移量置0,即从环境空间起点开始*/
for(buf_offset=0;true;env_offset++){
env_string[buf_offset]=peekb(environment,env_offset);
/*将环境空间中的字符逐个读入数组env_string中
if(env_string[buf_offset]){/*若为空字符,继续*/
buf_offset++;
continue;
}
if(!buf_offset) /*若buf_offset=0,则中个环境结束,回false*/
return false;
env_offset++;/*若为空字符,则一个环境字符串结束,回true*/
return true;
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.