The C language uses the cmd command and gets the output method

Source: Internet
Author: User

In practice, we sometimes need to use the C language to invoke the cmd command, and get the result of execution, here is a simple example.
#include <stdio.h>
Description: The Execmd function executes the command and stores the result in the results string arrayParameter: cmd indicates the command to execute//result is the result of the execution of the stored string array//function executed successfully returned 1, failed to return 0int Execmd (char* cmd,char* result) {  Char buffer[128];            Defining buffers              file* pipe = _popen (cmd, "R");     Open the pipeline and execute the command   if (!pipe) return 0;          Returning 0 indicates a failed run     while (!feof (pipe)) {  if (fgets (buffer, $, pipe)) {      Output pipe to result      strcat (Result,buffer);    }  }  _pclose (pipe);              Close pipe  return 1;                Returning 1 indicates a successful run}
int main () {  Char result[1024*4]= "";          Defines a string array that holds the result  if (1==execmd ("ipconfig", result)) {    printf (result);  }  System ("pause");             Pause to view results}In addition, Microsoft's MSDN documentation has more detailed instructions, interested friends can see: http://msdn.microsoft.com/en-us/library/96ayss4b (v=vs.80). aspx.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.