简体   繁体   中英

How many ways are there to execute system command in C program for windows

I am using MS visual studio 2008, for C coding.

I know we can use " int system(const char *command) " to execute commands.

Is there any other method to execute system commands in C program. Also I need to store output of executed command in a variable.

system() function execute command and send output to stdout , is there any way to read from stdout and store in variable.

So my ultimate goal is to execute system command in C program for windows (using visual studio) and store output of that command in a variable. Any suggestions ?

Standard C libraries give you only one way to execute external command in OS, so use int system(const char *command) .

You can save output of this command to text file, and then read this file from you program.

For example:

#include <stdio.h>
#include <stdlib.h>

#define TMP_FILE_NAME "TMP_FOLDER_CONTENT.txt"

int main(int argc, char *argv[])
{
    system("dir C:\* > "TMP_FILE_NAME);
    FILE * fdir = fopen(TMP_FILE_NAME, "r");
    char buff[100];
    if (fdir)
    {
        while (1) {
            if (fgets(buff, 100, fdir) == NULL) break;
            printf("%s", buff);
        }
    }
    fclose(fdir);
    remove(TMP_FILE_NAME);
    return 0;
}

Where dir is a program to be executed, C:\\* - argument of the program, and > - redirection of standard output for that command after which filename TMP_FOLDER_CONTENT.txt will be substituted.

Also you can check returned value, as:

int errorcode = system("dir C:\* > "TMP_FILE_NAME);
printf("Command executed and returned a value %d\n", errorcode);

or taking into account command you use, change the logic of your program, eg:

int errorcode = system("dir C:\* > "TMP_FILE_NAME);
if( errorcode )
{
   return errorcode;
}

UPDATE:

Alternatively, you could use pipes in C++, for example as shown in the answer to question How to execute a command and get output of command within C++ using POSIX?

您可以按照@VolAnd的说明进行操作,或者如果您不关心/不希望命令的输出位于stdout并且也不想将其他任何内容打印到stdout ,则可以使用freopen进行设置标准输出到您选择的文件。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM