Skip to content

A header-only C++ library for reading information from command-line parameters, .env files, and environment variables

License

Notifications You must be signed in to change notification settings

daotrungkien/cpp-dotenv

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Introduction

A header-only C++ library for reading information from (upper item having higher priority):

  • Command-line parameters (in the form: --VAR_NAME=VALUE, or --VAR_NAME)
  • .env file
  • Environment variables

Compatibility:

  • OSes: Windows, Linux
  • Compilers: g++, MS Visual C++ (with C++11 enabled)

Example

// Please compile and run the program with the following command to see the result:
//   ./test --VAR2=12345

#include "dotenv.h"
#include <iostream>

using namespace std;


int main(int argc, const char** argv) {
    // includes command-line arguments, environment variables,
    // files (`.env` in current folder, `.env` in program folder,
    // and `test-custom.env` file in program folder)
    dotenv env{argc, argv, true, {
        dotenv::in_current_folder(),
        dotenv::in_program_folder(),
        dotenv::in_program_folder("test-custom.env")
    }};

    // looks for variable from any source
    cout << "PATH = " << env["PATH"] << endl;
    cout << "VAR1 = " << env["VAR1"] << endl;
    cout << "VAR2 = " << env["VAR2"] << endl;
    cout << "VAR3 = " << env["VAR3"] << endl;

    // gets the value of VAR3 if existing, or a default value if not
    cout << "VAR3 (with default value) = " << env.get("VAR3", "default-var3") << endl;

    // checks if a variable exists in one specific source and prints its value if it does
    if (env.exists("VAR2", dotenv::source::environment))
        cout << "VAR2 = " << env.get("VAR2", dotenv::source::environment) << endl;
    else cout << "VAR2 is not set as an env variable" << endl;

    return 0;
}

About

A header-only C++ library for reading information from command-line parameters, .env files, and environment variables

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages