c程序中的echo变量

时间:2015-10-17 07:04:09

标签: c bash

我有一个用C语言(admin-secret)编写的程序,它有一个名为authenticate的函数。在这个函数里面有一个名为" result"的变量。如何使用另一个c程序回显此变量?
这样做的目的是使用strncmp返回值来猜测密码。

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

int main(int argc, char *argv[])
{     
    char command[1000] = {0};
    int result;
    sprintf(command, "/home/alice/Public/admin-secret %s; echo  %d", argv[1], result);
    system(command);
    printf("Result: %s\n" , result);
    return 0;
}

1 个答案:

答案 0 :(得分:1)

您需要创建一个管道,一种简单的方法是使用POSIX函数popen()

#include <stdio.h>

int main(int argc, char* argv[])
{
    FILE *pipe;
    char line[256];
    pipe = popen("ls", "r");
    if (pipe != NULL)
    {
        while (fgets(line, sizeof(line), pipe) != NULL)
            fprintf(stdout, "%s", line);
        pclose(pipe);
    }
    return 0;
}

您也可以使用sprintf() 1 构建命令,并将其作为第一个参数传递给popen(),这只是为了向您展示如何捕获输出另一个程序。

1 您应该使用snprintf()来防止目标数组溢出