C에서 환경 변수를 가져오고 설정하는 방법
접근법 1
이 방법에서는 단순히
environ 변수를 extern 키워드를 사용하여 확장하여 사용했습니다.암호
#include <stdio.h>
// https://man7.org/linux/man-pages/man7/environ.7.html
extern char **environ;
int main(int argc, char **argv) {
// list out all the environment variables
for (int i=0; environ[i]!=NULL; i++) {
printf("%d: %s\n", i, envp[i]);
}
return 0;
}
자세한 내용은
environ man page을 확인하십시오.접근법 2
대부분의 학생들은
main 함수가 환경 변수 배열에 불과한 세 번째 인수를 받을 수도 있다는 사실을 모릅니다.NOTE: The third argument may not support all compilers. But it should work on the latest compiler versions.
암호
#include <stdio.h>
int main(int argc, char **argv, char **envp) {
// list out all the environment variables
for (int i=0; envp[i]!=NULL; i++) {
printf("%d: %s\n", i, envp[i]);
}
return 0;
}
접근법 3
이 방법에서는 정의된
getenv 및 setenv 함수를 사용합니다.getenv는 환경 변수 이름인 하나의 인수를 사용하고 null로 끝나는 char 포인터를 반환합니다. 전달된 이름이 없으면 NULL 를 반환합니다.setenv는 세 가지 인수를 사용합니다. 첫 번째는 환경 변수 이름이고 두 번째는 해당 값이고 세 번째는 0이 아닌 경우 이미 존재하는 환경 변수를 같은 이름으로 덮어쓰는 int 플래그입니다.NOTE:
setenvdoesn't set the environment variable permanently but for the current process and its child process only. It meanssetenvthe environment variables are visible only in the current process and its child ones.
더 많은 작업을 보려면
clearenv 및 man page의 putenv와 같은 다른 기능을 확인하십시오.암호
#include <stdio.h>
#include <stdlib.h> // setenv, getenv
int main(int argc, char **argv) {
char *user = getenv("USER"),
*hosttype = getenv("HOSTTYPE"),
*hostname = getenv("HOSTNAME");
printf("USER: %s\n", user ? user : "null");
printf("HOSTTYPE: %s\n", hosttype ? hosttype : "null");
printf("HOSTNAME: %s\n", hostname ? hostname : "null");
setenv("USER", "namantam1", 1);
printf("updated USER: %s\n", getenv("USER"));
return 0;
}
산출
USER: naman
HOSTTYPE: x86_64
HOSTNAME: null
updated USER: namantam1
신청
❤️이 글을 읽어주셔서 정말 감사합니다. 저는 새로운 것을 배우는 열정적인 공대생이므로 실수를 발견하거나 제안할 사항이 있으면 댓글로 알려주세요.
또한 이 게시물이 어떤 식으로든 도움이 된다면 공유하고 엄지손가락을 치켜세우는 것을 고려하십시오.
Reference
이 문제에 관하여(C에서 환경 변수를 가져오고 설정하는 방법), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/namantam1/ways-to-get-and-set-environment-variables-in-c-200m텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)