Posted on 2006-03-18 21:59
天涯浪子 閱讀(1538)
評論(0) 編輯 收藏 引用
/*變量p用來存放自己定義的環境變量,而pt用來存放系統環境變量的PATH值
注意:此例應該先判斷變量的返回值是否為空
取得環境變量函數的格式如下:
?char* getenv(const char *name);?return value for environment name.
?
?int putenv(const char* str);?change or add value to environment.
*/
#include <stdlib.h>
#include <iostream>
using namespace std;
int main(){
?char *p = NULL;
?char *pt=NULL;
?
?p = getenv( "AAA" );
?pt =getenv("PATH");
?
?if( p == NULL )
??cout<<"No such env named AAA"<<endl;
?else
??cout<<"AAA=" << p << endl;
?if( pt == NULL )
??cout<<"No such env named PATH"<<endl;
?else
??cout<<"PATH=" << pt<< endl;
?putenv( "AAA=123456" );
?cout<<"AAA=" << getenv( "AAA" ) << endl;
?putenv("AAA=123");
?cout<<"AAA="<<getenv("AAA")<<endl;
?
?cout<<"PATH="<<getenv("PATH")<<endl;
?return 0 ;
}
/*問題:
?假如環境變量YU在用戶的shell下的值是123456,在我們的應用程序中
?通過getenv()和putenv()來更改該環境變量為abcdef,那么當我們結束應用
?程序后回到shell下時,我們用命令echo $YU,那么結果應該是什么?
*/