Namespace: Tiny::OS
- Module Overview
- Header File
- Data Structures
- System Information Functions
- FileSystem Class
- Usage Examples
- Notes
The OS::System module provides system information retrieval and file system operation functionality:
- System Information: CPU, memory, disk, host information retrieval
- File System: Directory creation, file copy/move/delete, path traversal
// CMake method
#include <Tiny/OS/System.hpp>
// Direct source copy method
#include "OS/System.hpp"p.s: On Windows, when compiling a single file, you need to manually include the pdh and advapi32 static libraries.
constexpr const char* Name("...");Description: Current operating system name constant, automatically defined based on compilation platform.
| Platform | Value |
|---|---|
| Windows | "windows" |
| Linux | "linux" |
| macOS | "apple" |
| Unix | "unix" |
| Android | "android" |
| FreeBSD | "FreeBSD" |
| Others | "unknown" |
Usage Example:
#include "OS/System.hpp"
#include <iostream>
int main() {
std::cout << "Current OS: " << Tiny::OS::Name << std::endl;
return 0;
}struct HostInfo {
std::string host_name; // Host name
std::string user_name; // Current user name
std::string os_name; // Operating system name
std::string machine; // Machine architecture
std::string version; // System version
};| Field | Type | Description |
|---|---|---|
host_name |
std::string |
Computer name on the network |
user_name |
std::string |
Current logged-in user name |
os_name |
std::string |
Operating system name (e.g., "Windows 10", "Ubuntu") |
machine |
std::string |
Hardware architecture (e.g., "x86_64") |
version |
std::string |
Operating system version number |
enum class CPU_Arch {
Unknown = 0,
X86 = 1,
X86_64 = 2,
ARM32 = 3,
ARM64 = 4,
LoongArch = 5, // Loongson architecture
MIPS = 6, // MIPS architecture
RISCV = 7, // RISC-V architecture
IA64 = 8 // Intel Itanium
};struct CPU {
CPU_Arch machine; // CPU architecture
uint32_t cores; // Number of cores
uint32_t page_size; // Memory page size (bytes)
float total_usage; // Total usage percentage
std::vector<float> usages; // Per-core usage
};| Field | Type | Description |
|---|---|---|
machine |
CPU_Arch |
CPU architecture type |
cores |
uint32_t |
Number of logical cores |
page_size |
uint32_t |
System memory page size |
total_usage |
float |
Total CPU usage (0-100) |
usages |
std::vector<float> |
Usage of each core |
struct Memory {
size_t total_ram; // Total physical memory
size_t free_ram; // Free physical memory
size_t available_ram; // Available physical memory
size_t used_ram; // Used physical memory
size_t total_swap; // Total swap space
size_t free_swap; // Free swap space
// macOS specific fields
size_t app_free_mem; // Application free memory
size_t app_active_mem; // Active memory
size_t app_inactive_mem; // Inactive memory
size_t app_wired_mem; // Wired memory
size_t app_compress_mem; // Compressed memory
size_t app_speculative_mem; // Speculative memory
};| Field | Type | Description | Platform Support |
|---|---|---|---|
total_ram |
size_t |
Total physical memory (bytes) | All |
free_ram |
size_t |
Completely free memory (bytes) | All |
available_ram |
size_t |
Available memory for applications (bytes) | All |
used_ram |
size_t |
Used memory (bytes) | All |
total_swap |
size_t |
Total swap space (bytes) | All |
free_swap |
size_t |
Free swap space (bytes) | All |
app_* |
size_t |
macOS specific memory statistics | macOS only |
struct DiskSpace {
size_t total_bytes; // Total capacity
size_t free_bytes; // Free capacity
size_t used_bytes; // Used capacity
size_t available_bytes; // Available capacity (considering reserved space)
};const char* getCPUArchName(CPU_Arch cpu_arch);- Function: Get CPU architecture name string
- Parameter:
cpu_arch- CPU architecture enum value - Return Value: Architecture name (e.g., "x86_64", "arm64")
HostInfo currentHostInfo();- Function: Get current host information
- Return Value:
HostInfostructure
CPU currentCPUInfo();- Function: Get current CPU information
- Return Value:
CPUstructure - Notes: Getting usage has a brief delay (about 50ms)
Memory currentMemory();- Function: Get current memory information
- Return Value:
Memorystructure
DiskSpace currentDiskSpace();- Function: Get current disk space information
- Return Value:
DiskSpacestructure
bool getHostInfo(HostInfo& info);- Function: Get host information to reference parameter
- Parameter:
info- Output parameter - Return Value:
truemeans success
bool getCPUInfo(CPU& info, size_t internal = 50);- Function: Get CPU information
- Parameter:
info- Output parameterinternal- Sampling interval (milliseconds), default 50ms
- Return Value:
truemeans success
bool getMemory(Memory& memory);- Function: Get memory information
- Parameter:
memory- Output parameter - Return Value:
truemeans success
bool getDiskSpace(DiskSpace& disk_space);- Function: Get disk space information
- Parameter:
disk_space- Output parameter - Return Value:
truemeans success
CPU_Arch getCurrentCPUArch();- Function: Get current CPU architecture
- Return Value:
CPU_Archenum value
void lastSystemError(std::string& info, int* err_code = nullptr);- Function: Get the last system error information
- Parameters:
info- Output parameter, receives the error description stringerr_code- Optional output parameter, receives the error code (defaultnullptr)
- Return Value: None
- Notes:
- On Windows, uses
GetLastError()andFormatMessageA()to retrieve the error - On Unix/Linux, uses
errnoandstrerror()to retrieve the error - This function retrieves the error of the most recent system call
- On Windows, uses
bool isAdmin();- Function: Check whether the current process is running with administrator/root privileges
- Return Value:
truemeans running with administrator/root privileges - Notes:
- On Windows, checks whether the current user is a member of the Administrators group
- On Unix/Linux, checks whether the effective user ID is 0 (root)
int exec(const std::string& command, size_t timeout_ms = 0,
std::string* output = nullptr, std::string* error = nullptr);-
Function: Execute an external command and wait for it to finish, with timeout control and output capture support
-
Parameters:
command- Command line string to execute. On Windows it is passed directly toCreateProcess; on Unix/Linux it is split into an argument array on whitespace (arguments containing spaces can be wrapped in single or double quotes) and executed viaexecvp, which searches for the executable inPATHtimeout_ms- Timeout in milliseconds. Defaults to0, which means wait indefinitely until the command finishes. When the command times out:- Windows: the entire process tree is terminated via a Job Object, with exit code 127
- Unix/Linux:
SIGTERMis sent to the process group first; if it is still alive after 5 seconds,SIGKILLis sent
output- Optional output parameter. When non-nullptr, receives the command's standard output (stdout); whennullptr, the child process inherits the parent's standard outputerror- Optional output parameter. When non-nullptr, receives the command's standard error (stderr); whennullptr, the child process inherits the parent's standard error
-
Return Value: The exit code of the command process. Special values:
Return Value Meaning 0 - 255Normal exit code of the command process -1Internal error (e.g., pipe creation failure, forkfailure, or emptycommandstring)-2Windows only: the process could not be started (program does not exist or is not an executable file) 127The command was terminated due to timeout; on Unix/Linux this also covers failure to execute the command ( execvpfailure) or abnormal termination by a signal -
Notes:
- The strings pointed to by
outputanderrorare cleared before the call - This function does not go through a system shell (no
cmd.exeon Windows, no/bin/shon Unix/Linux), so shell syntax such as pipes, redirections, and wildcards is not supported - The function blocks the current thread until the command finishes or times out
- The strings pointed to by
Provides static file system operation functions, including directory creation, file copy/move/delete, path traversal, etc.
static bool chDir(const Path& path);
static bool chDir(const std::string& path);- Function: Change current working directory
- Parameter:
path- Target directory path - Return Value:
truemeans success
static bool mkDir(const Path& path);
static bool mkDir(const std::string& path);- Function: Create directory
- Parameter:
path- Directory path - Return Value:
truemeans success - Constraint: Parent directory must exist
static bool mkFile(const Path& path, const std::vector<uint8_t>& data = {});
static bool mkFile(const std::string& path, const std::vector<uint8_t>& data = {});
static bool mkFile(const Path& path, const std::string& data);
static bool mkFile(const std::string& path, const std::string& data);- Function: Create file (with optional initial content)
- Parameter:
path- File pathdata- Initial content (optional)
- Return Value:
truemeans success
static bool mkLink(const std::string& path, const std::string& link_dest);
static bool mkLink(const std::string& path, const Path& link_dest);- Function: Create symbolic link
- Parameter:
path- Link pathlink_dest- Target path
- Return Value:
truemeans success
static bool cpFile(const Path& src, const Path& dest);
static bool cpFile(const Path& src, const std::string& dest);- Function: Copy file
- Parameter:
src- Source file pathdest- Destination path
- Return Value:
truemeans success
static bool cpDir(const Path& src, const Path& dest);
static bool cpDir(const Path& src, const std::string& dest);- Function: Copy directory (recursive)
- Parameter:
src- Source directory pathdest- Destination path
- Return Value:
truemeans success
static bool mvFile(const Path& src, const Path& dest);
static bool mvFile(const Path& src, const std::string& dest);- Function: Move/rename file
- Parameter:
src- Source file pathdest- Destination path
- Return Value:
truemeans success
static bool mvDir(const Path& src, const Path& dest);
static bool mvDir(const Path& src, const std::string& dest);- Function: Move/rename directory
- Parameter:
src- Source directory pathdest- Destination path
- Return Value:
truemeans success
static bool rmFile(const Path& path);
static bool rmFile(const std::string& path);- Function: Delete file
- Parameter:
path- File path - Return Value:
truemeans success
static bool rmDir(const Path& path, bool recursion = false);
static bool rmDir(const std::string& path, bool recursion = false);- Function: Delete directory
- Parameter:
path- Directory pathrecursion- Whether to recursively delete contents, default false
- Return Value:
truemeans success - Constraint: Directory must be empty in non-recursive mode
static Path currentPath();- Function: Get current working directory
- Return Value: Path object of current directory
static Path homePath();- Function: Get user home directory
- Return Value: Path object of user home directory
static Path cachePath();- Function: Get user cache directory
- Return Value: Path object of cache directory (
~/.cacheor Windows equivalent)
static Path localDataPath();- Function: Get user local data directory
- Return Value: Path object of local data directory (
~/.local/shareor Windows equivalent)
static std::vector<Path> listPath(const Path& path,
uint8_t recursion_count = 1,
const std::function<bool(const Path&)>& filter = {});
static std::vector<Path> listPath(const std::string& path,
uint8_t recursion_count = 1,
const std::function<bool(const Path&)>& filter = {});
static std::vector<Path> listPath(uint8_t recursion_count = 1,
const std::function<bool(const Path&)>& filter = {});- Function: List directory contents
- Parameter:
path- Target directory path (optional, defaults to current directory)recursion_count- Recursion depth, 0 or 255 means unlimited, default 1 (current level only)filter- Filter function (optional)
- Return Value: Array of Path objects
using LayerMap = std::unordered_map<size_t, std::vector<Path>>;
static LayerMap listPathEx(const Path& path,
uint8_t recursion_count = 1,
const std::function<bool(const Path&, bool&)>& found_event = {});
static LayerMap listPathEx(const std::string& path,
uint8_t recursion_count = 1,
const std::function<bool(const Path&, bool&)>& found_event = {});- Function: Enhanced directory traversal with layered results organized by depth
- Parameter:
path- Target directory pathrecursion_count- Recursion depth, 0 or 255 means unlimited, default 1 (current level only)found_event- Callback function (optional) that receives:const Path&- Current path being traversedbool& stop- Set totrueto halt traversal immediately
- Return Value:
LayerMap(unordered_map<size_t, vector>) where the key is the depth level (0 = root directory, 1 = first subdirectory level, etc.) and the value is an array of Path objects at that depth - Notes:
- Unlike
listPath, this method organizes results by directory depth - The
found_eventcallback allows early termination by setting thestopparameter totrue - Useful for hierarchical directory analysis or depth-limited searches
- Unlike
#include "OS/System.hpp"
#include <iostream>
int main() {
// Host information
auto host = Tiny::OS::currentHostInfo();
std::cout << "Host name: " << host.host_name << std::endl;
std::cout << "User name: " << host.user_name << std::endl;
std::cout << "OS: " << host.os_name << " " << host.version << std::endl;
// CPU information
auto cpu = Tiny::OS::currentCPUInfo();
std::cout << "Architecture: " << Tiny::OS::getCPUArchName(cpu.machine) << std::endl;
std::cout << "Cores: " << cpu.cores << std::endl;
std::cout << "Usage: " << cpu.total_usage << "%" << std::endl;
// Memory information
auto mem = Tiny::OS::currentMemory();
std::cout << "Total RAM: " << mem.total_ram / 1024 / 1024 << " MB" << std::endl;
std::cout << "Available RAM: " << mem.available_ram / 1024 / 1024 << " MB" << std::endl;
// Disk information
auto disk = Tiny::OS::currentDiskSpace();
std::cout << "Total capacity: " << disk.total_bytes / 1024 / 1024 / 1024 << " GB" << std::endl;
std::cout << "Available capacity: " << disk.available_bytes / 1024 / 1024 / 1024 << " GB" << std::endl;
return 0;
}#include "OS/System.hpp"
#include <iostream>
int main() {
using namespace Tiny::OS;
// Create directory
FileSystem::mkDir("./test_dir");
// Create file
FileSystem::mkFile("./test_dir/file.txt", "Hello, World!");
// Copy file
FileSystem::cpFile("./test_dir/file.txt", "./test_dir/file_copy.txt");
// List directory
auto files = FileSystem::listPath("./test_dir");
for (const auto& f : files) {
std::cout << f.shortFileName() << std::endl;
}
// Delete files and directory
FileSystem::rmFile("./test_dir/file.txt");
FileSystem::rmFile("./test_dir/file_copy.txt");
FileSystem::rmDir("./test_dir");
// Get special paths
std::cout << "Home: " << FileSystem::homePath().path() << std::endl;
std::cout << "Current: " << FileSystem::currentPath().path() << std::endl;
return 0;
}#include "OS/System.hpp"
#include <iostream>
int main() {
using namespace Tiny::OS;
// Recursively list all .cpp files
auto cpp_files = FileSystem::listPath("./src", 255,
[](const Path& p) {
return p.extensionName() == "cpp";
});
std::cout << "Found " << cpp_files.size() << " .cpp files:" << std::endl;
for (const auto& f : cpp_files) {
std::cout << " " << f.path() << std::endl;
}
// Only traverse one level
auto current_files = FileSystem::listPath("./src", 1);
return 0;
}#include "OS/System.hpp"
#include <iostream>
#include <thread>
int main() {
Tiny::OS::CPU cpu;
for (int i = 0; i < 10; ++i) {
Tiny::OS::getCPUInfo(cpu, 500); // Sample 500ms
std::cout << "Total usage: " << cpu.total_usage << "%" << std::endl;
std::cout << "Per-core usage: ";
for (size_t j = 0; j < cpu.usages.size(); ++j) {
std::cout << "Core" << j << ":" << cpu.usages[j] << "% ";
}
std::cout << std::endl;
}
return 0;
}#include "OS/System.hpp"
#include <iostream>
int main() {
std::string output, error;
// Capture stdout and stderr of the command, with a 5 second timeout
int code = Tiny::OS::exec("git --version", 5000, &output, &error);
std::cout << "Exit code: " << code << std::endl;
std::cout << "Stdout: " << output << std::endl;
if (!error.empty()) {
std::cout << "Stderr: " << error << std::endl;
}
// Without capturing output: the child's stdout/stderr go directly to the current terminal
// timeout_ms keeps the default value 0, meaning wait until the command finishes
Tiny::OS::exec("git status");
return 0;
}getCPUInfo()requires sampling interval (default 50ms)- Call blocks for the specified time
- Longer sampling intervals yield more accurate results
- Windows uses Performance Counter API
- Unix/Linux reads
/proc/stat - macOS uses
host_statistics()
- Windows: Uses
GlobalMemoryStatusEx() - Linux: Reads
/proc/meminfo - macOS: Uses
host_statistics64(), provides additional memory categories
- Creating/deleting directories requires write permission
- Cross-filesystem moves may fail
- Symbolic link creation requires administrator privileges (Windows)
- Recursive traversal of large numbers of files may be slow
- Use filter functions to reduce returned results
- Depth-first traversal
| Path | Windows | Unix/Linux | macOS |
|---|---|---|---|
| Home | %USERPROFILE% |
$HOME |
$HOME |
| Cache | %LOCALAPPDATA%\cache |
~/.cache |
~/Library/Caches |
| Local Data | %LOCALAPPDATA% |
~/.local/share |
~/Library/Application Support |
- All functions return
boolindicating success/failure - No exceptions thrown
- Failure reasons can be obtained via system error codes (platform dependent)