c++ 调用cmd命令行函数 可隐藏黑框 四种方法总结 | 您所在的位置:网站首页 › 怎样取消文件隐藏窗口 › c++ 调用cmd命令行函数 可隐藏黑框 四种方法总结 |
在很多情况下,不得不调用cmd命令行,去实现一系列功能,总结靠谱方法两种如下: 方法一:可接受cmd命令行黑框一闪(推荐星数::可传值几乎任何cmd命令)string string getCmdResult(const string &strCmd)//传参string格式命令,返回值string格式; { char buf[10240] = { 0 }; FILE *pf = NULL; if ((pf = _popen(strCmd.c_str(), "r")) == NULL) { return ""; } string strResult; while (fgets(buf, sizeof buf, pf)) { strResult += buf; } _pclose(pf); unsigned int iSize = strResult.size(); if (iSize > 0 && strResult[iSize - 1] == '\n') { strResult = strResult.substr(0, iSize - 1); } return strResult; } 方法二:隐藏CMD黑窗 (推荐星数::可传值大部分cmd命令,如ipconfig、ping等,具体请自测)直接调用此函数string ExeCmd(string pszCmd)即可,传命令为string格式,返回值仍为 string格式。 重点:部分命令,传形参命令时必须加入 cmd.exe /c 具体请自测。(这个让我走了好几天弯路百思不得其解,最后意外发现此方法可解决,免去了把文件导出来,一行读取判断的麻烦!) 例如:改变文件编码格式命令 type 1.txt>2.txt 传形参时应该这样传参 cmd.exe /c type 1.txt>2.txt #include #include //#pragma comment( linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"" )//隐藏命令行 #include #include #include using namespace std; wstring Str2Wstr(string str) { unsigned len = str.size() * 2;// 预留字节数 setlocale(LC_CTYPE, ""); //必须调用此函数 wchar_t *p = new wchar_t[len];// 申请一段内存存放转换后的字符串 mbstowcs(p, str.c_str(), len);// 转换 std::wstring str1(p); delete[] p;// 释放申请的内存 return str1; } string ExeCmd(string pszCmd) { wstring pszCmd_w = Str2Wstr(pszCmd); wcout |
今日新闻 |
推荐新闻 |
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 |