方式:#ifdef _LINUX #else #endif
#ifdef _LINUX
const char* cmdline = "ifconfig";
#else
const char* cmdline = "ipconfig";
#endif
#include <stdio.h>
// 返回: -1, 命令行出错; >=0, 实际输出的字节数
int execute(const char* cmdline, char* output, int maxsize)
{
// 执行命令, 获取输出流
#ifdef _WIN32
FILE* fp = _popen(cmdline, "r");
#else
FILE* fp = popen(cmdline, "r");
#endif
if(!fp) return -1;
// 读取maxsize-1个字节
int size = 0; // 已读取的字节数
maxsize -= 1;
while(!feof(fp))
{
int n = fread(output+size, 1, maxsize - size, fp);
if(n<=0) break;
size += n;
}
// 关闭输出
#ifdef _WIN32
_pclose(fp);
#else
pclose(fp);
#endif
output[size] = 0;
return size; // 实际读取的字节数
}
int main()
{
char buf[1024];
/*
#ifdef _WIN32
const char* cmdline = "ipconfig";
#else
const char* cmdline = "ifconfig";
#endif
*/
#ifdef _LINUX
const char* cmdline = "ifconfig";
#else
const char* cmdline = "ipconfig";
#endif
int n = execute(cmdline, buf, 1024);
if(n> 0)
{
buf[n] = 0;
printf("------ output -------\n");
printf("%s\n", buf);
}
return 0;
}
参考