windows和linux下获取当前程序路径以及cpu数

本文介绍了一个跨平台的C++程序,用于获取当前应用程序的路径及系统的CPU核心数。通过条件编译实现Windows与类Unix系统(如Linux、macOS)上的兼容性。在Windows上使用`GetModuleFileName`和`GetSystemInfo`函数,在类Unix系统上则通过读取`/proc`文件系统和调用`sysconf`函数。

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

[cpp]  view plain copy
 
  1. #ifdef WIN32  
  2. #include <Windows.h>  
  3. #else  
  4. #include <stdio.h>  
  5. #include <unistd.h>  
  6. #endif  
  7.   
  8. #include <assert.h>  
  9.   
  10.     std::string getCurrentAppPath()  
  11.     {  
  12. #ifdef WIN32  
  13.         char path[MAX_PATH + 1] = {0};  
  14.         if (GetModuleFileName(NULL, path, MAX_PATH) != 0)  
  15.             return std::string(path);  
  16. #else  
  17.         char path[256] = {0};  
  18.         char filepath[256] = {0};  
  19.         char cmd[256] = {0};  
  20.         FILE* fp = NULL;  
  21.   
  22.         // 设置进程所在proc路径  
  23.         sprintf(filepath, "/proc/%d", getpid());  
  24.         // 将当前路径设为进程路径  
  25.         if(chdir(filepath) != -1)  
  26.         {  
  27.             //指定待执行的shell 命令  
  28.             snprintf(cmd, 256, "ls -l | grep exe | awk '{print $10}'");  
  29.             if((fp = popen(cmd,"r")) == NULL)  
  30.             {  
  31.                 return std::string();  
  32.             }  
  33.             //读取shell命令执行结果到字符串path中  
  34.             if (fgets(path, sizeof(path)/sizeof(path[0]), fp) == NULL)  
  35.             {  
  36.                 pclose(fp);  
  37.                 return std::string();  
  38.             }  
  39.   
  40.             //popen开启的fd必须要pclose关闭  
  41.             pclose(fp);  
  42.             return std::string(path);  
  43.         }  
  44. #endif  
  45.         return std::string();  
  46.     }  
  47.   
  48.     std::size_t getCpuCount()  
  49.     {  
  50. #ifdef WIN32  
  51.         SYSTEM_INFO sysInfo;  
  52.         GetSystemInfo(&sysInfo);  
  53.         return sysInfo.dwNumberOfProcessors;  
  54. #else  
  55.         long cpu_num = sysconf(_SC_NPROCESSORS_ONLN);  
  56.         if (cpu_num == -1)  
  57.         {  
  58.             assert(false);  
  59.             return 0;  
  60.         }  
  61.         // 看两者是否相等  
  62.         assert(cpu_num == sysconf(_SC_NPROCESSORS_CONF));  
  63.         return cpu_num;  
  64. #endif  
  65.     }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值