C庫 - getenv() 函式



C 的stdlibgetenv() 函式在與當前程序關聯的環境變數列表中搜索由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!
廣告
© . All rights reserved.