Linux C语言实现获取设备运行时间并转换成xxdxxhxxmxxs的格式
时间: 2024-03-17 22:45:21 浏览: 71
可以使用下面的代码实现将系统运行时间转换成 `xxdxxhxxmxxs` 格式:
```c
#include <stdio.h>
#include <stdlib.h>
#define SECONDS_PER_DAY 86400
#define SECONDS_PER_HOUR 3600
#define SECONDS_PER_MINUTE 60
int main() {
double uptime;
int days, hours, minutes, seconds;
FILE *fp = fopen("/proc/uptime", "r");
if (fp == NULL) {
perror("Unable to read uptime\n");
exit(EXIT_FAILURE);
}
fscanf(fp, "%lf", &uptime);
fclose(fp);
days = (int)(uptime / SECONDS_PER_DAY);
hours = (int)((uptime - days * SECONDS_PER_DAY) / SECONDS_PER_HOUR);
minutes = (int)((uptime - days * SECONDS_PER_DAY - hours * SECONDS_PER_HOUR) / SECONDS_PER_MINUTE);
seconds = (int)(uptime - days * SECONDS_PER_DAY - hours * SECONDS_PER_HOUR - minutes * SECONDS_PER_MINUTE);
printf("System uptime: %dd%02dh%02dm%02ds\n", days, hours, minutes, seconds);
return 0;
}
```
这个程序首先计算出运行时间对应的天数、小时数、分钟数和秒数,然后使用格式字符串 `%dd%02dh%02dm%02ds` 打印出结果,其中 `%02d` 表示输出两位数字,不足两位时前面补零。
阅读全文