简体   繁体   English

Windows的C程序中执行系统命令的方式有几种

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

I am using MS visual studio 2008, for C coding. 我正在使用MS visual studio 2008进行C编码。

I know we can use " int system(const char *command) " to execute commands. 我知道我们可以使用“ int system(const char *command) ”来执行命令。

Is there any other method to execute system commands in C program. 还有其他方法可以在C程序中执行系统命令。 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. system()函数执行命令并将输出发送到stdout ,有什么方法可以从stdout读取并存储在变量中。

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. 因此,我的最终目标是在Windows的C程序中执行系统命令(使用Visual Studio)并将该命令的输出存储在变量中。 Any suggestions ? 有什么建议么 ?

Standard C libraries give you only one way to execute external command in OS, so use int system(const char *command) . 标准C库仅提供一种在OS中执行外部命令的方法,因此请使用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. 其中dir是要执行的程序, C:\\* -该程序的参数, > -该命令的标准输出重定向,之后将替换文件名TMP_FOLDER_CONTENT.txt

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? 或者,您可以使用C ++中的管道,例如,如问题解答中所示, 如何使用POSIX在C ++中执行命令并获取命令输出?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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