Various useful util-linux fn/headers that I cn use to make my c/cpp prg easy: (chatGpt Answers)

Query:

various useful util-linux fn/headers that I cn use to make my c/cpp prg easy

Reply:

Excellent and very practical question 👏 — especially for Linux system-level C/C++ work.

util-linux is a huge, battle-tested toolkit of system utilities (mount, fdisk, uuidgen, etc.) and library functions you can use to make your programs more powerful and consistent with Linux internals.

Below is a compact developer-oriented reference of the useful functions and headers you can directly leverage from util-linux (and related system libraries that ship with it).


🧩 1️⃣ Core Library — <uuid/uuid.h> (libuuid)

Library: libuuid
Link: -luuid
Purpose: UUID generation, parsing, and comparison.

Useful Functions:

uuid_generate(uuid_t out); // generate random/time-based UUID uuid_generate_random(uuid_t out); uuid_generate_time(uuid_t out); uuid_unparse_lower(uuid_t uu, char *out); // to string uuid_parse(const char *in, uuid_t uu); // from string uuid_compare(a, b); uuid_is_null(uu);

Use: Unique IDs, session keys, distributed object IDs, etc.


🧩 2️⃣ <blkid/blkid.h> — libblkid

Library: libblkid
Link: -lblkid
Purpose: Identify and query block devices (disks, partitions, filesystems).

Useful Functions:

blkid_probe_new_from_filename("/dev/sda1"); blkid_probe_lookup_value(pr, "UUID", &uuid, NULL); blkid_get_tag_value(NULL, "/dev/sda1", "TYPE");

Use:
Detect filesystem types, UUIDs, labels, mount points — great for system monitors or installers.


🧩 3️⃣ <mount.h> — libmount

Library: libmount
Link: -lmount
Purpose: Manage and parse mount tables (/etc/mtab, /proc/self/mountinfo).

Useful Functions:

struct libmnt_table *tb = mnt_new_table(); mnt_table_parse_mtab(tb, NULL); struct libmnt_iter *itr = mnt_new_iter(MNT_ITER_FORWARD); mnt_table_next_fs(tb, itr, &fs); mnt_fs_get_target(fs); // e.g., /mnt/data mnt_fs_get_source(fs); // e.g., /dev/sda1

Use:
Check what’s mounted, unmount/mount filesystems programmatically.


🧩 4️⃣ <smartcols.h> — libsmartcols

Library: libsmartcols
Link: -lsmartcols
Purpose: Nicely format tables/columns for CLI tools (used by lsblk, lsns, etc.).

Useful Functions:

struct libscols_table *tb = scols_new_table(); scols_table_new_column(tb, "NAME", 10, SCOLS_FL_RIGHT); scols_table_new_column(tb, "VALUE", 20, 0); scols_table_new_line(tb, &ln); scols_line_set_data(ln, 0, "Disk"); scols_line_set_data(ln, 1, "/dev/sda"); scols_table_print(tb);

Use:
Pretty CLI tabular outputs (aligned like system tools).


🧩 5️⃣ <fdisk.h> — libfdisk

Library: libfdisk
Link: -lfdisk
Purpose: Low-level disk partitioning and metadata operations.

Useful Functions:

fdisk_new_context(); fdisk_assign_device(cxt, "/dev/sda", 1); fdisk_get_label(cxt); fdisk_table_list_partitions(cxt);

Use:
Writing partitioning tools, installers, or storage management scripts.


🧩 6️⃣ <uuid/uuid.h> + <blkid/blkid.h> combo

Use together to correlate filesystem and device UUIDs.

Example: map /dev/sda1 → filesystem UUID.


🧩 7️⃣ <libsmartcols> + <mntent.h> combo

Create lsblk-like table of currently mounted filesystems.


🧩 8️⃣ <pathnames.h>, <sys/mount.h>, <sys/statvfs.h>

These are standard Linux headers but complement util-linux libs.

Use:

  • mount(), umount()

  • statvfs() for filesystem stats

  • constants like _PATH_MOUNTED


🧩 9️⃣ <libfdisk> Helpers for GPT/MBR parsing

Purpose: inspect partition types, sizes, alignments, GPT GUIDs.


🧩 🔟 <libsmartcols> with color support

Purpose: build colorful CLI outputs with auto-width columns — like lsblk.


⚙️ Install dev headers (if not present)

sudo apt install uuid-dev libblkid-dev libmount-dev libsmartcols-dev libfdisk-dev

⚙️ Example: Combining UUID + Smartcols

#include <uuid/uuid.h> #include <smartcols.h> #include <iostream> int main() { uuid_t uuid; char str[37]; uuid_generate(uuid); uuid_unparse_lower(uuid, str); struct libscols_table *tb = scols_new_table(); scols_table_new_column(tb, "Field", 10, 0); scols_table_new_column(tb, "Value", 36, 0); struct libscols_line *ln; scols_table_new_line(tb, &ln); scols_line_set_data(ln, 0, "UUID"); scols_line_set_data(ln, 1, str); scols_table_print(tb); scols_unref_table(tb); }

Compile:

g++ -std=c++23 main.cpp -luuid -lsmartcols

Output:

Field | Value ------+------------------------------------ UUID | 550e8400-e29b-41d4-a716-446655440000

✅ Summary Table

LibHeaderLinkPurpose
libuuid<uuid/uuid.h>-luuidUUID generation
libblkid<blkid/blkid.h>-lblkidDetect block devices/filesystems
libmount<mount.h>-lmountManage mount tables
libsmartcols<smartcols.h>-lsmartcolsPretty-print tables
libfdisk<fdisk.h>-lfdiskPartition table manipulation

Would you like me to generate a single C++ “util-linux helper header” (e.g. util_linux_helpers.hpp) wrapping the above in a modern, RAII-safe C++23 interface (namespace util::linuxsys)?
It’ll give you functions like listMountedFS(), generateUUID(), prettyPrintTable(), etc.

-------------------------------------============

Q: any prebuilt existing lib in posix/linux/ubuntu to give colored console output
ChatGPT said:

Excellent follow-up 👏 — this is a common need for tools and daemons that want rich colored or styled console output without adding heavy dependencies.

Let’s go over what’s already built-in or preinstalled on Ubuntu/POSIX systems — no external downloads — and how you can use them cleanly from C/C++.


🧩 1️⃣ ANSI Escape Sequences (✅ Pure POSIX Built-In)

This is the standard, fastest, and portable method.

No headers, no libraries — works everywhere (Linux, macOS, BSD, even most terminals on Windows 10+).

#include <iostream> int main() { std::cout << "\033[1;31mRed Bold Text\033[0m\n"; std::cout << "\033[32mGreen\033[0m and \033[34mBlue\033[0m text.\n"; }
CodeMeaning
\033[0mReset
\033[1mBold
\033[4mUnderline
\033[30–37mForeground colors
\033[40–47mBackground colors
\033[90–97mBright foreground
\033[100–107mBright background

Advantages

  • POSIX-compliant

  • No dependency

  • Works in all terminal emulators

⚙️ Best for:
System tools, daemons, or CLI utilities.


🧩 2️⃣ <term.h> + libtinfo / libncurses (✅ POSIX-compatible)

Purpose: Terminal capability control (color, cursor, etc.)
Header: <term.h>
Link: -lncurses (or -ltinfo for low-level terminfo)

Example:

#include <iostream> #include <term.h> #include <curses.h> void init_term() { setupterm(NULL, fileno(stdout), NULL); putp(tigetstr("bold")); putp(tparm(tigetstr("setaf"), 2)); // Green std::cout << "Hello, world!\n"; putp(tigetstr("sgr0")); // Reset } int main() { init_term(); }

Advantages

  • Terminal-safe (queries terminfo, doesn’t assume ANSI)

  • Works on non-ANSI terminals (e.g., serial consoles)

  • Part of base Ubuntu (comes with ncurses-base)

Install dev headers:

sudo apt install libtinfo-dev

⚙️ Best for:
Programs where you must respect TERM type and avoid raw escape codes (e.g., vi, top, ls).


🧩 3️⃣ ncurses (✅ Fully preinstalled, POSIX-ish)

Header: <ncurses.h>
Link: -lncurses
Purpose: Full terminal UI — windows, colors, key input.

Example:

#include <ncurses.h> int main() { initscr(); start_color(); init_pair(1, COLOR_RED, COLOR_BLACK); attron(COLOR_PAIR(1) | A_BOLD); printw("Red Bold Text\n"); attroff(COLOR_PAIR(1) | A_BOLD); refresh(); getch(); endwin(); }

Advantages

  • Built into all Linux distros

  • Safe, portable, battle-tested

  • Rich API (color, windows, mouse, key input, etc.)

⚙️ Best for:
Full-screen TUIs, dashboards, terminal GUIs.


🧩 4️⃣ libsmartcols (from util-linux) — 🧩 Styled columns

Header: <smartcols.h>
Link: -lsmartcols

Example (optional color support):

scols_table_enable_colors(tb, 1); scols_column_set_color(col, "green");

Advantages

  • Built-in with util-linux

  • Automatically respects terminal capabilities and color output (same lib used by lsblk)

⚙️ Best for:
When printing tables, aligned outputs with colors (lsblk-style).


🧩 5️⃣ termcap (legacy, POSIX optional)

Header: <termcap.h>
Link: -ltermcap

Legacy system (superseded by terminfo/ncurses).
Avoid for new code.


Summary Table

LibraryHeaderLinkStatusFeaturesNotes
ANSI escapesnonenone✅ POSIXFast, simpleFor modern terminals
terminfo / term.h<term.h>-ltinfo✅ POSIXColor-safeLow-level terminal caps
ncurses<ncurses.h>-lncurses✅ PreinstalledFull TUI + colorFor dashboards
libsmartcols<smartcols.h>-lsmartcols✅ util-linuxColored tableslsblk style
termcap<termcap.h>-ltermcap⚠️ ObsoleteLegacyAvoid

⚙️ Recommendation for You (C/C++ Dev)

For modern CLI tools (e.g., trading system status output, logs, etc.):

  • Use ANSI escape sequences for simple highlighting.

  • For safety (when stdout isn’t a TTY), wrap with:

    #include <unistd.h> if (isatty(fileno(stdout))) std::cout << "\033[32mOK\033[0m\n"; else std::cout << "OK\n";
  • For structured colored tables → libsmartcols.

  • For interactive UI dashboards → ncurses.


Would you like a small header-only console_color.hpp that wraps this neatly — auto-detects terminal color support, provides util::color::red("text") etc., and falls back to plain text when redirected to file (non-TTY)?

No comments:

Post a Comment

If you have any doubts, please let me know.

Various types of salts effect on health (discussion with gemenie)

Is  rock salt or bitnoon helps in digestion or just a airuvedic nuska This is for informational purposes only. For medical advice or diagnos...