运行cmd命令并将结果保存到一个字符串变量中
Running cmd commands and getting results to a string variable is a common problem in programming. One of the standard solutions for this problem is to use command line redirection to send the standard output to a text file, and then read the file into a string.
However, this approach may not be suitable for all programming languages or environments. For example, in C/C++, you could use the _popen() function to execute the command and retrieve the output. In .NET, there might be other ways to achieve this, as mentioned in a Stack Overflow answer linked in the provided context.
The mentioned Stack Overflow answer discusses redirecting console output to a textbox in a separate program using C#. This approach might not be the standard solution, as another commenter suggests. Instead, they argue that the standard solution would be to send the standard output to a pipe and read it from there, eliminating the need to interact with the file system.
However, another commenter points out that this solution might only apply to the Unix/C branch of history. In the MSDOS/Windows 3/VB/Access branch, pipes were not available, but command line redirection was. They attribute the confusion to the lack of context provided in the original question.
In conclusion, the standard solution for running cmd commands and getting results to a string variable can vary depending on the programming language and environment. Command line redirection to a text file and reading it into a string is one approach, but alternatives like using _popen() or working with pipes may be more suitable in certain contexts.
问题的出现原因是:需要在程序中运行命令并将结果保存到一个字符串变量中。
解决方法是:使用相关的函数和命令来实现这个功能。
对于Linux系统,可以使用popen函数来创建一个管道,然后将命令的输出结果读取到一个字符串变量中。具体的代码如下:
#include#include #include int main() { FILE* fp = popen("ifconfig", "r"); if(fp) { std::vector buffer(4096); std::size_t n = fread(buffer.data(), 1, buffer.size(), fp); if(n && n < buffer.size()) { buffer.data()[n] = 0; std::cout << buffer.data() << '\n'; } pclose(fp); } }
对于Windows系统,可以使用"_popen"函数,并将命令改为"ipconfig"来实现相同的功能。具体的代码如下:
#include#include #include int main() { FILE* fp = _popen("ipconfig", "r"); if(fp) { std::vector buffer(4096); std::size_t n = fread(buffer.data(), 1, buffer.size(), fp); if(n && n < buffer.size()) { buffer.data()[n] = 0; std::cout << buffer.data() << '\n'; } _pclose(fp); } }
通过使用这些代码,可以在程序中运行命令并将结果保存到一个字符串变量中。