c系统函数在其他字符串之前获取

时间:2016-03-26 09:46:48

标签: c system

我正在尝试编写一个打印C编译器版本的简单c程序。所以我写道:

#include <stdio.h>
int main() {
    printf("you have %d", system("gcc --version");
}

输出:

gcc (Ubuntu 4.8.4-2ubuntu1~14.04.1) 4.8.4
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

you have compiler 0

任何想法?

3 个答案:

答案 0 :(得分:1)

<div class="ext"> <div class="flex"> <div class="flexItem"> <p class="text"> Aaaaa aaaaa aaaa aaaaa aaa aaaaaaa aaaaa aa aaa aaaaaaa aaaaaaaaa aaaa aaaaa aaa aaaaaaa aaaaa aa aaa aaaaaaa aaaaaaaaa aaaa aaaaa aaa aaaaaaa aaaaa aa aaa aaaaaaa aaaaaaaaa aaaa aaaaa aaa aaaaaaa aaaaa aa aaa aaaaaaa aaaa </p> </div> <div class="flexItem"> <img class="image" src="http://i.telegraph.co.uk/multimedia/archive/03439/dude6_3439641b.jpg" /> </div> </div> </div>执行shell命令并返回命令的状态。在您的情况下,值为0表示命令已成功运行。

答案 1 :(得分:1)

您对printf的来电正在打印system来电的返回值。根据{{​​3}},系统调用的返回值是被调用命令的返回状态(在这种情况下为gcc)。

由于对gcc的调用成功,返回值为“0”。那么,这是您的程序打印的值:

you have compiler 0

答案 2 :(得分:0)

像这样:

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

int main() {
    FILE* fp;
    unsigned major, minor, build;
    system("gcc --version > gccoutput.txt");

    fp = fopen("gccoutput.txt", "r");
    if (fp) {
        fscanf(fp, "gcc (GCC) %u.%u.%u", &major, &minor, &build);
        printf("Major: %u, minor: %u, build: %u\n", major, minor, build);
        fclose(fp);
    }
}

我的输出是gcc(GCC)4.6.2等

因此,对于您的输出,您将不得不改变。或者在x.y.z

之前使其适用于任何字符串

更灵活的解决方案可以使用:

fscanf(fp, "%[A-Za-z() ]%u.%u.%u", s, &major, &minor, &build);

是一个char缓冲区。