Reference

Programming languages

Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.

Scope and conventions

TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.

Libraries: system & OS

The operating system around a program: arguments and environment, files and paths, streams, child processes, signals, platform information, command-line options and logging.

Process, arguments & environment: process, os, std::env, <cstdlib>

C++

C++ receives arguments as main's argc and argv parameters, not through a library. <cstdlib> supplies std::getenv (nullptr when the variable is unset), std::exit and the EXIT_SUCCESS and EXIT_FAILURE codes; <filesystem> supplies current_path. There is no standard option parser or process-spawning API; libraries such as CLI11 and Boost.Process fill those gaps.

Complete program

Complete program. Standard library: ships with your compiler, no install.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cstdlib>
#include <filesystem>
#include <print>
#include <string>
#include <vector>

int main(int argc, char* argv[]) {
    std::vector<std::string> args(argv + 1, argv + argc); // argv[0] is the program
    const char* raw = std::getenv("PORT"); // nullptr when unset
    std::string port = raw ? raw : "3000";

    std::println("{} args, port {}", args.size(), port);
    std::println("cwd: {}", std::filesystem::current_path().string());
    return EXIT_SUCCESS;
}

Most used: int main(int argc, char* argv[]), std::getenv, return EXIT_FAILURE, std::filesystem::current_path, std::system for running a shell command.

Files & paths: node:fs, os + path/filepath, std::fs, <filesystem>

C++

<filesystem> (C++17) works with paths and directories: path with operator/ for joining, create_directories, exists, directory_iterator, remove and file_size. File contents are read and written with streams from <fstream>: std::ifstream reads, std::ofstream writes. Filesystem functions throw filesystem_error unless you pass a std::error_code.

Complete program

Complete program. Standard library: ships with your compiler, no install.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <filesystem>
#include <fstream>
#include <print>
#include <string>

namespace fs = std::filesystem;

int main() {
    fs::path dir = fs::path("data") / "reports"; // platform separator
    fs::create_directories(dir);

    fs::path file = dir / "today.txt";
    std::ofstream(file) << "total: 3\n"; // the temporary stream closes here

    std::ifstream in(file);
    std::string line;
    std::getline(in, line);

    std::println("{} {}", file.filename().string(), file.extension().string());
    std::println("{}", line);
}

Most used: std::filesystem::path, operator/, create_directories, exists, directory_iterator, std::ifstream with std::getline, std::ofstream <<.

Embedding, temp files, globs & watching: fs.glob, embed + os.MkdirTemp, tempfile, #embed

C++

<filesystem> covers temp files only partly: temp_directory_path() returns the system temp directory, but nothing creates a uniquely named entry atomically, so POSIX mkdtemp and mkstemp (or a random name with create_directory, which reports whether it created the directory) fill the gap. There is no glob: walk with directory_iterator or recursive_directory_iterator and filter on extension or filename. #embed, which includes a file's bytes as an initializer list, is standard in C23 and C++26 (not C++23); Clang already accepts it in C++ as an extension, with a -Wc23-extensions warning, and older toolchains use xxd -i or a CMake step to generate a source file. There is no standard file watcher: inotify (Linux), FSEvents or kqueue (macOS), ReadDirectoryChangesW (Windows), or a wrapper such as efsw.

Complete program

Complete program for Clang (#embed in C++ is a Clang extension).

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <algorithm>
#include <filesystem>
#include <fstream>
#include <print>
#include <random>
#include <string>
#include <string_view>
#include <vector>

namespace fs = std::filesystem;

int main() {
#if defined(__has_embed) && __has_embed("main.cpp")
    static constexpr unsigned char source[] = {
#embed "main.cpp"
    };
    std::string_view text(reinterpret_cast<const char*>(source), sizeof source);
    std::println("{}", text.substr(0, text.find('\n'))); // this file's first line
#else
    std::println("no #embed");
#endif

    // No mkdtemp in the standard: pick a random name; create_directory reports a clash.
    fs::path dir = fs::temp_directory_path() / ("reports-" + std::to_string(std::random_device{}()));
    if (!fs::create_directory(dir)) return 1;
    fs::create_directory(dir / "2026");
    for (auto name : {"a.csv", "b.csv", "notes.txt", "2026/c.csv"}) std::ofstream(dir / name) << 'x';

    std::vector<std::string> found; // "**/*.csv" by hand
    for (const auto& entry : fs::recursive_directory_iterator(dir))
        if (entry.is_regular_file() && entry.path().extension() == ".csv")
            found.push_back(entry.path().lexically_relative(dir).generic_string());
    std::ranges::sort(found);
    std::println("{}", found);
    fs::remove_all(dir); // temp dirs are not cleaned up for you
}

Most used: temp_directory_path, create_directory, recursive_directory_iterator, path::extension, lexically_relative, remove_all, mkdtemp, #embed with __has_embed, xxd -i.

Clang warns "#embed is a Clang extension [-Wc23-extensions]" in C++ mode; the program falls back to a message on compilers without __has_embed.

#embed paths are searched like #include paths, relative to the including file first.

directory_iterator order is unspecified; sort the results when order matters.

Streams & buffered input: node:readline, io + bufio, std::io, <iostream>

C++

<iostream> provides the standard streams std::cin, std::cout, std::cerr and std::clog. >> reads whitespace-separated values, std::getline reads a whole line and << writes. File streams (<fstream>) and string streams (<sstream>) share the same interface, so code written against std::istream or std::ostream works with all of them.

Complete program

Complete program. Standard library: ships with your compiler, no install.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <iostream>
#include <stdexcept>
#include <string>

// Read standard input line by line, e.g. `cat numbers.txt | ./app`.
int main() {
    long total = 0;
    std::string line;
    while (std::getline(std::cin, line)) {
        try {
            total += std::stol(line);
        } catch (const std::exception&) { // invalid_argument or out_of_range
            // skip lines that are not numbers (note: stol accepts "12abc" as 12)
        }
    }
    std::cout << "total: " << total << '\n';
}

Most used: std::getline(std::cin, line), std::cin >> value, std::cout <<, std::istringstream for parsing a line, std::ios::sync_with_stdio(false) for large inputs.

Running other programs: child_process, os/exec, std::process::Command, popen

C++

The C++ standard library has no process API beyond std::system, which runs a shell command and returns its status. On POSIX systems, popen and pclose (shown) read a command's output through a pipe, and posix_spawn starts a program with an argument array. Boost.Process and reproc wrap these portably with argument lists, pipes and timeouts.

Complete program

Complete program for POSIX systems (macOS, Linux).

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <array>
#include <cstdio>
#include <print>
#include <string>

// popen runs the command through /bin/sh: never build it from untrusted input.
std::string run(const char* command, int& status) {
    std::string output;
    FILE* pipe = popen(command, "r");
    if (!pipe) return output;
    std::array<char, 256> buffer;
    while (std::fgets(buffer.data(), buffer.size(), pipe)) output += buffer.data();
    status = pclose(pipe); // an encoded wait status; 0 means success
    return output;
}

int main() {
    int status = -1;
    std::string listing = run("ls -1 /", status);
    std::println("{} entries listed, status {}", !listing.empty(), status);
}

Most used: std::system, popen and pclose, posix_spawnp with waitpid, boost::process::v2::process, reproc::process.

Signals & graceful shutdown: process signals, os/signal, tokio::signal, <csignal>

C++

<csignal> installs handlers with std::signal for SIGINT, SIGTERM and the other standard signals. A handler may only do async-signal-safe work, so the usual pattern is to set a lock-free std::atomic flag (or a volatile std::sig_atomic_t) (or write to a pipe) and let the main loop notice it and shut down cleanly. POSIX sigaction gives finer control, and Boost.Asio's signal_set delivers signals as ordinary asynchronous events.

Complete program

Complete program. Standard library: ships with your compiler, no install.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <atomic>
#include <chrono>
#include <csignal>
#include <print>
#include <thread>

// A handler may only do async-signal-safe work, so it just sets a flag.
std::atomic<bool> stop_requested{false};
static_assert(std::atomic<bool>::is_always_lock_free); // required for use in a handler

extern "C" void on_signal(int) { stop_requested = true; }

int main() {
    std::signal(SIGINT, on_signal); // Ctrl-C
    std::signal(SIGTERM, on_signal); // service managers and containers

    std::jthread demo([] { // demo: signal ourselves
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        std::raise(SIGTERM);
    });

    while (!stop_requested) { // the main loop notices the flag
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
    std::println("signal received, shutting down");
}

Most used: std::signal, SIGINT, SIGTERM, std::atomic<bool> flags, sigaction, boost::asio::signal_set, std::jthread stop tokens.

Platform info & reflection: node:os, runtime + reflect, cfg/std::mem, <type_traits>

C++

C++ asks most of these questions at compile time. <type_traits> inspects types (is_integral_v, is_trivially_copyable_v, remove_cvref_t), sizeof and alignof report layout, and preprocessor macros such as __linux__, _WIN32 and __APPLE__ select platform code. At run time, std::thread::hardware_concurrency reports cores and std::filesystem::temp_directory_path the temp directory; std::source_location (C++20) and std::stacktrace (C++23; MSVC ships it, libstdc++ needs -lstdc++exp, libc++ lacks it) help with diagnostics.

Complete program

Complete program. Standard library: ships with your compiler, no install.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <filesystem>
#include <print>
#include <source_location>
#include <thread>
#include <type_traits>

struct Order {
    int id;
    bool paid;
    long total;
};

template <class T>
void describe(const T&) {
    // Type traits answer questions about types at compile time.
    std::println("{} bytes, trivially copyable: {}, integral: {}", sizeof(T),
                 std::is_trivially_copyable_v<T>, std::is_integral_v<T>);
}

int main() {
    std::println("{} hardware threads", std::thread::hardware_concurrency()); // 0 if unknown
    std::println("{}", std::filesystem::temp_directory_path().is_absolute());
    describe(Order{});
    describe(42);

    auto here = std::source_location::current(); // file and line without macros
    std::println("line {}", here.line());
#if defined(__APPLE__)
    std::println("built for Apple platforms");
#endif
}

Most used: <type_traits> *_v traits, sizeof, alignof, if constexpr, platform macros, std::thread::hardware_concurrency, std::source_location::current, std::stacktrace::current where supported.

Command-line options: util.parseArgs, flag, clap, CLI11

C++

C++ has no option parser: main receives argc and argv. CLI11 (header-only) is the common modern choice, with options bound to variables, short and long names, validation, subcommands and generated --help. cxxopts is a lighter alternative, Boost.Program_options is common in older code, and getopt is the POSIX C function.

Complete program

Complete program; try: ./app --port 8080 -v orders.csv

Before you use this

Not in the standard library: CLI11 (header-only) from vcpkg, Conan, Homebrew or a vendored CLI11.hpp.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <CLI/CLI.hpp>
#include <print>
#include <string>

int main(int argc, char** argv) {
    CLI::App app{"Serve orders from a CSV file"};

    int port = 3000;
    bool verbose = false;
    std::string file;
    app.add_option("-p,--port", port, "Port to listen on");
    app.add_flag("-v,--verbose", verbose, "Log every request");
    app.add_option("file", file, "Input file")->required();

    CLI11_PARSE(app, argc, argv); // prints help or an error and exits when needed
    std::println("{} {} {}", port, verbose, file);
}

Most used: CLI::App, add_option, add_flag, ->required(), ->check(CLI::Range(...)), add_subcommand, CLI11_PARSE.

Logging: console, log/slog, tracing, std::clog

C++

There is no logging library in the C++ standard. std::clog (buffered) and std::cerr (unbuffered) from <iostream> both write to standard error, and projects often wrap them in a small function like this one. For levels, sinks, rotation and fast formatting, spdlog (built on the {fmt} library) is the most common choice; glog and Boost.Log are alternatives.

Complete program

Complete program. Standard library: ships with your compiler, no install.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <chrono>
#include <format>
#include <iostream>
#include <string_view>

void log(std::string_view level, std::string_view message) {
    auto now = std::chrono::floor<std::chrono::seconds>(std::chrono::system_clock::now());
    std::clog << std::format("{:%FT%TZ} {} {}\n", now, level, message);
}

int main() {
    log("INFO", "server starting");
    log("WARN", "cache disabled");
    std::cerr << "connect failed\n"; // unbuffered error stream
}

Most used: std::clog, std::cerr, a small log() wrapper with std::format, spdlog::info and spdlog::error in larger projects.