首页 > 解决方案 > 从 C system() 函数返回字符串

问题描述

我刚刚学习了 C 并且对指针很着迷。最近我发现了 C 函数system()。我能够从我通过system(" program.exe") 执行的程序中获取返回值。例如,program.c

#include <stdio.h>

int main(){
    printf("hello world\n");

    return 123;
}

这段代码program.exe调用call.c

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

int main(){
    int a;
    printf("calling program.exe:\n");
    a=system("program.exe");
    printf("program.exe returned %d at exit\n",a);

    return 0;
}

当我执行call.exe时,我得到了这个

calling program.exe:
hello world
pm returned 123 at exit

我当时想,哇!这个返回值和system()函数对我来说就像是一种新的进程间通信方式。system()但我的问题是,我可以从函数中获得字符串返回吗?

我尝试将program.cint main()”更改为“ char * main()”,并将“”更改return 123为“ ”,将格式更改为in ,但我只在执行 call.exe 时得到有趣的字符。我想知道怎么了?return "bohemian rhapsody"int a;char *a;printf%d%scall.c

标签: cstringsystemipc

解决方案


不,您不能从 中返回字符串system(),事实上,大多数现代桌面操作系统下的程序在终止时只能“返回”一个整数退出代码。

如果您确实想从执行的程序中取回字符串,一种方法是使用popen()来调用程序,然后让该程序将字符串写入stdout.


推荐阅读