c - 从 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.c
“ int main()
”更改为“ char * main()
”,并将“”更改return 123
为“ ”,将格式更改为in ,但我只在执行 call.exe 时得到有趣的字符。我想知道怎么了?return "bohemian rhapsody"
int a;
char *a;
printf
%d
%s
call.c
解决方案
不,您不能从 中返回字符串system()
,事实上,大多数现代桌面操作系统下的程序在终止时只能“返回”一个整数退出代码。
如果您确实想从执行的程序中取回字符串,一种方法是使用popen()
来调用程序,然后让该程序将字符串写入stdout
.
推荐阅读
- android - 使用 Rx 测试房间插入时测试失败
- java - JPA:即使在 FetchType.LAZY 之后也有 N+1 个查询
- java - 如何在多模块项目中使用 JUnit5 和 SpringBoot2 通过 gradle 而不是 intelliJ 运行测试
- android - 如何在textView中设置顶部和底部drawablePadding
- java - Java Spark 应用程序给出错误:org.apache.spark.SparkException: Failed to get broadcast_1_piece0 of broadcast_1
- python - 无法使用 python 从 selenium 中的 datepicker 日历中选择日期
- javascript - 如何选择单击的复选框的值?
- kubernetes - Kubernetes PV 在删除/重新创建后拒绝绑定
- python-3.x - Windows 上的 Anaconda 3 混合了 32 位和 64 位版本?
- r - 使用 rvest 从网站上抓取表格