====== تابع ()getenv و ()setenv - خواندن و نوشتن متغیر های محلی ====== ---- ==== تابع ()getenv ==== // man 1 env // man 3 getenv /* getenv() returns a pointer to the value in the environment, or NULL if there is no match. */ #include char *getenv(const char *name); /* env-var.c */ #include #include #include int main(void) { /* Using getenv() to fetch env. variables */ printf("Your username is %s\n", getenv("USER")); printf("Your home directory is %s\n", getenv("HOME")); printf("Your preferred editor is %s\n", getenv("EDITOR")); printf("Your shell is %s\n", getenv("SHELL")); /* Check if the current terminal support colors*/ if ( strstr(getenv("TERM"), "256color") ) { /* Color the output with \033 + colorcode */ printf("\033[0;31mYour \033[0;32mterminal " "\033[0;35msupport " "\033[0;33mcolors\033[0m\n"); } else { printf("Your terminal doesn't support" " colors\n"); } return 0; } $ make env-var cc env-var.c -o env-var $ ./env-var Your username is pejman Your home directory is /home/pejman Your preferred editor is (null) Your shell is /bin/bash Your terminal support colors $ echo $USER pejman $ echo $HOME /home/pejman $ echo $EDITOR $ echo $SHELL /bin/bash $ echo $TERM xterm-256color $ export TERM=xterm $ ./env-var Your username is pejman Your home directory is /home/pejman Your preferred editor is (null) Your shell is /bin/bash Your terminal doesn't support colors $ export TERM=xterm-256color $ echo $TERM xterm-256color $ TERM=xterm ./env-var Your username is pejman Your home directory is /home/pejman Your preferred editor is (null) Your shell is /bin/bash Your terminal doesn't support colors $ echo $TERM xterm-256color ---- ==== تابع ()setenv ==== // man 3 setenv /* The setenv() function adds the variable name to the environment with the value value. * if variable exists and overwrite is zero, then the value of name is not changed. */ #include int setenv(const char *name, const char *value, int overwrite); /* env-var-set.c */ #define _POSIX_C_SOURCE 200112L #include #include int main(void) { setenv("FULLNAME", "Jack-Benny", 1); printf("Your full name is %s\n", getenv("FULLNAME")); return 0; } $ make env-var-set cc env-var-set.c -o env-var-set $ ./env-var-set Your full name is Jack-Benny $ echo $FULLNAME