C++ 调用cmd命令 和 执行程序

方法一:使用 _popen(管道)执行程序
  • _popen 的头文件为 #include<stdio.h>

  • 使用 _popen 函数写的 exe_cmd() 可以获得命令的返回值,但是 system 函数不行。

  • 直接调用 exe_cmd() 即可执行程序。

    string exe_cmd(const char *cmd)
    {
    	char buffer[128] = { 0 };
    	string result;
    	FILE *pipe = _popen(cmd, "r");
    	if (!pipe) throw std::runtime_error("_popen() failed!");
    	while (!feof(pipe))
    	{
    		if (fgets(buffer, 128, pipe) != NULL)
    			result += buffer;
    	}
    	_pclose(pipe);
    	return result;
    }
    
实例
  • 显示计算器

    #include<bits/stdc++.h>
    using namespacestd;
    int main(int argc, char *argv[])
    {
    	exe_cmd("calc");
    	return 0;
    }
    
方法二:使用 system 执行程序
  • 使用system不能返回信息。

  • 存在黑框,会闪过

    #include <bits/stdc++.h>
    using namespace std;
    int main(int argc, char *argv[])
    {
    	system("calc");
    	return 0;
    }
    
结果

命令窗口执行完,会弹出计算器按钮。

存在问题
  • 使用dev编译的时候,会提示不是内部命令。但是使用 VS2017 的时候不会出现问题。
    (发现可能是由于路径的问题,使用绝对路径后,问题解决。)
  • 路径中存在空格的时候,可以使用 “ ” 将命令包起来
  • 注意路径上一些符号需要转义
发布了119 篇原创文章 · 获赞 20 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qq_40727946/article/details/103516313