- C标准库
- C库 - 首页
- C库 - <assert.h>
- C库 - <complex.h>
- C库 - <ctype.h>
- C库 - <errno.h>
- C库 - <fenv.h>
- C库 - <float.h>
- C库 - <inttypes.h>
- C库 - <iso646.h>
- C库 - <limits.h>
- C库 - <locale.h>
- C库 - <math.h>
- C库 - <setjmp.h>
- C库 - <signal.h>
- C库 - <stdalign.h>
- C库 - <stdarg.h>
- C库 - <stdbool.h>
- C库 - <stddef.h>
- C库 - <stdio.h>
- C库 - <stdlib.h>
- C库 - <string.h>
- C库 - <tgmath.h>
- C库 - <time.h>
- C库 - <wctype.h>
C库 - getenv() 函数
C 的stdlib 库 getenv() 函数在与当前进程关联的环境变量列表中搜索由name指向的环境字符串。它通过我们提供的名称找到匹配项。如果找到匹配项,它将返回一个指向包含该环境变量值的C字符串的指针。
环境变量是用户可定义的值,可以影响计算机进程的运行行为。
语法
以下是getenv()函数的C库语法:
char *getenv(const char *name)
参数
此函数接受单个参数:
name − 它表示包含指定变量名称的C字符串。
返回值
如果存在环境变量,则此函数返回一个以null结尾的字符串;否则,它返回NULL。
示例1
在这个例子中,我们创建了一个基本的c程序来演示getenv()函数的使用。
#include <stdlib.h>
#include <stdio.h>
int main() {
// Name of the environment variable (e.g., PATH)
const char *name = "PATH";
// Get the value associated with the variable
const char *env_p = getenv(name);
if(env_p){
printf("Your %s is %s\n", name, env_p);
}
return 0;
}
输出
以下是输出:
Your PATH is /opt/swift/bin:/usr/local/bin/factor:/root/.sdkman/candidates/kotlin/current/bin:/usr/GNUstep/System/Tools:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/usr/local/scriba/bin:/usr/local/smlnj/bin:/usr/local/bin/std:/usr/local/bin/extra:/usr/local/fantom/bin:/usr/local/dart/bin:/usr/libexec/sdcc:/usr/local/icon-v950/bin:/usr/local/mozart/bin:/opt/Pawn/bin:/opt/pash/Source/PashConsole/bin/Debug/:.:/root/.sdkman/candidates/kotlin/current/bin:/usr/bin:/sbin:/bin
示例2
让我们创建另一个示例,我们检索path "tutorialspoint"环境变量的值。如果它存在。否则,我们显示“环境变量不存在!”。
#include <stdlib.h>
#include <stdio.h>
int main() {
// name of the environment
const char* env_variable = "tutorialspoint";
// Retrieve the value
char* value = getenv(env_variable);
if (value != NULL) {
printf("Variable = %s \nValue %s", env_variable, value);
} else {
printf("Environment Variable doesn't exist!");
}
return 0;
}
输出
以下是输出:
Environment Variable doesn't exist!
广告