std::getenv(3)
Hey bestie π welcome to std::getenv(3) from the C++ Standard Libary manual β yes, thatβs the manual name up top, and weβre folding it in right here instead of copying the header line. Letβs get into it π«Ά
πΈ NAME πΈ
std::getenv β std::getenv. Thatβs literally the name, bestie β¨
β¨ Synopsis β¨
Defined in header <cstdlib>
char* getenv( const char* env_var );
Okay so what it does π: it searches the environment list provided by the host environment (the OS) for a string that matches the C string pointed to by env_var, and returns a pointer to the C string that is associated with the matched environment list member. Slay.
Thread-safety tea β: this function is not required to be thread-safe. (until C++11) Another call to getenv, as well as a call to the POSIX functions setenv(), unsetenv(), and putenv(), may invalidate the pointer returned by a previous call or modify the string obtained from a previous call.
This function is thread-safe (calling it from multiple threads does not introduce a data race) as long as no other function modifies the host environment. (since C++11) In particular, the POSIX functions setenv(), unsetenv(), and putenv() would introduce a data race if called without synchronization.
And please, bestie β modifying the string returned by getenv invokes undefined behavior. π Not cute, not iconic, do not do it.
π Parameters π
env_varβ a null-terminated character string identifying the name of the environmental variable to look for π
π Return value π
A character string identifying the value of the environmental variable β or a null pointer if such variable is not found. Simple as that π¦
π¦ Notes π¦
On POSIX systems, the environment variables are also accessible through the global variable environ, declared as extern char** environ; in <unistd.h>, and through the optional third argument, envp, of the main function. iykyk π
π₯ Example π₯
// Run this code
#include <cstdlib>
#include <iostream>
int main()
{
if (const char* env_p = std::getenv("PATH"))
std::cout << "Your PATH is: " << env_p << '\n';
}
Possible output:
Your PATH is: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
π See also π
C documentation for getenv π§
Signed, sealed, delivered, bestie π
: this page comes from http://cppreference.com, dated 2024.06.10, and itβs page std::getenv(3). Mwah π
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms