unix/linux获取信息函数--例子

本文介绍了一个简单的C++程序,该程序能够获取并显示当前系统的详细信息,包括系统名称、版本、主机名以及当前的时间日期等。通过调用如uname、gethostname和time等函数,展示了如何在C++中收集这些重要的系统参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. #include <algorithm>
  2. #include <iterator>
  3. #include <iostream>
  4. #include <string>
  5. #include <sys/types.h>
  6. #include <pwd.h>
  7. #include <grp.h>
  8. #include <sys/utsname.h>
  9. #include <time.h>
  10. #include <unistd.h>
  11. int main(int argc, char* argv[])
  12. {
  13.     struct utsname name;
  14.     if (uname(&name) == -1)
  15.     {
  16.         perror("uname failure");
  17.         return -1;    
  18.     }
  19.     std::cout<<name.machine<<std::endl;
  20.     std::cout<<name.sysname<<std::endl;
  21.     std::cout<<name.version<<std::endl;
  22.     std::cout<<name.release<<std::endl;
  23.     char hostname[100];
  24.     if (gethostname(hostname, sizeof(hostname)) == -1)
  25.     {
  26.         perror("gethostname failure");
  27.         return -1;
  28.     }
  29.     std::cout<<hostname<<std::endl;
  30.     time_t long_time;
  31.     if (time(&long_time) == -1)
  32.       {
  33.         perror("time fialure");
  34.         return -1;
  35.       }
  36.     std::cout<<long_time<<std::endl;
  37.     struct tm* ptr_tm;
  38.     if ((ptr_tm=localtime(&long_time)) == NULL)
  39.       {
  40.         perror("localtime fialure");
  41.         return -1;
  42.       }
  43.     std::cout<<"current year is:"<<ptr_tm->tm_year+1900<<std::endl;//year since 1900
  44.     std::cout<<"current month is:"<<ptr_tm->tm_mon+1<<std::endl;//mon is in[0, 11]
  45.     std::cout<<"current day is:"<<ptr_tm->tm_mday<<std::endl;
  46.     std::cout<<"current hour is:"<<ptr_tm->tm_hour<<std::endl;
  47.     std::cout<<"current min is:"<<ptr_tm->tm_min<<std::endl;
  48.     std::cout<<"current second is:"<<ptr_tm->tm_sec<<std::endl;
  49.     std::cout<<"current weekday is:"<<ptr_tm->tm_wday<<std::endl;//wday since sunday[0, 6]
  50.     
  51. }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值