【C/C++】程式中如何執行作業系統命令?
在我們編寫C或者C++程式時候,有時候會碰到要求執行作業系統命令或者其他應用程式,同時要麼需要獲取命令執行的輸出,要麼不需要獲取命令執行的輸出,針對這兩點,我分別各介紹一方式
1: 方法一: system 函式
直接上示例大家更容易理解:
if (0 != system("/bin/echo \"hello world\""))
{
printf("%s", "system failed");;
}
2: 方法二: popen 函式
同上,直接上示例:
char tmpstring[512] = {0};
std::string cmdstring = "/bin/echo \"hello world\" "
FILE* fp = popen(cmdstring.c_str(), "r");
if (NULL == fp)
{
printf("%s", "popen failed");
exit(-1);
}
memset_s(tmpstring, sizeof(tmpstring), 0, sizeof(tmpstring));
if (fgets(tmpstring, (int)sizeof(tmpstring), fp) != NULL)
{
tmpstring[strlen(tmpstring) - 1] = 0;
}
pclose(fp);
fp = NULL;
在我們編寫C或者C++程式時候,有時候會碰到要求執行作業系統命令或者其他應用程式,同時要麼需要獲取命令執行的輸出,要麼不需要獲取命令執行的輸出,針對這兩點,我分別各介紹一方式