On Linux, it can be useful to know when the system was last booted, for example, to troubleshoot system issues or to monitor system uptime. This tutorial shows how to get the last system boot date and time on Linux using C++.
The /proc/uptime
file contains information about the system uptime. The file contains a single line of text that consists of two values separated by a space. The first value represents the total number of seconds that the system has been running since it was last booted. The second value represents the amount of time that the system has spent idle in seconds.
We open the /proc/uptime
file and read the number of seconds that the system has been running. Then we subtract this value from the current time to get the time of the last boot. Next, we use the localtime
function for conversion to the local date and time. Using the strftime
function, the date and time is formatted as a string. Finally, we output the formatted boot date and time to the console.
#include <iostream>
#include <fstream>
#include <ctime>
int main()
{
std::ifstream file("/proc/uptime");
double uptimeSeconds;
file >> uptimeSeconds;
std::time_t lastBootTime = std::time(nullptr) - (std::time_t) uptimeSeconds;
char buf[20];
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", localtime(&lastBootTime));
std::cout << buf << std::endl;
return 0;
}
Here's an example of the output:
2023-05-01 06:48:05
Leave a Comment
Cancel reply