我想使用 linux的“base64”脚本对数据进行编码并在C中获取. 当我尝试编译 char a[200];strcpy(a, "Hello");printf("%s", a); 我得到了输出 Hello 现在,每当我尝试代码 char a[200];strcpy(a, system("echo Hello
当我尝试编译
char a[200];
strcpy(a, "Hello");
printf("%s", a);
我得到了输出
Hello
现在,每当我尝试代码
char a[200];
strcpy(a, system("echo Hello | base64"));
printf("%s", a);
我得到了输出
aGVsbG8K Segmentation fault
即使我删除了“printf”语句,我也是如此
aGVsbG8K Segmentation fault
我想保存输出的值
system("echo Hello | base64")
在’a’而不显示它.请帮忙
这里strcpy(a, system("echo Hello | base64"));
system()不会将其结果存储到数组a中,因为system()作业是执行参数&中提供的命令.将它打印在控制台上,即stdout缓冲区.从system的手册页
system()executes a command specified incommandby calling
/bin/sh -c
command, and returns after the command has been completed.
有一种方法可以解决这个问题,即不是在stdout上打印system()输出,而是可以将其输出重定向到文件&然后从文件&中读取打印.例如
int main(void) {
close(1); /* stdout file descriptor is avilable now */
/* create the file if doesn't exist, if exist truncate the content to 0 length */
int fd = open("data.txt",O_CREAT|O_TRUNC|O_RDWR,0664); /* fd gets assigned with lowest
available fd i.e 1 i.e nowonwards stdout output
gets rediredcted to file */
if(fd == -1) {
/* @TODO error handling */
return 0;
}
system("echo Hello | base64"); /* system output gets stored in file */
int max_char = lseek(fd,0,2);/* make fd to point to end, get the max no of char */
char *a = malloc(max_char + 1); /* to avoid buffer overflow or
underflow, allocate memory only equal to the max no of char in file */
if(a == NULL) {
/* @TODO error handling if malloc fails */
return 0;
}
lseek(fd,0,0);/* from beginning of file */
int ret = read(fd,a,max_char);/* now read out put of system() from
file as array and print it */
if(ret == -1) {
/* @TODO error handling */
return 0;
}
a[ret] = '\0';/* \0 terminated array */
dup2(0,fd);/*fd 0 duplicated to file descriptor where fd points i.e */
printf("output : %s \n", a);
/* to avoid memory leak, free the dynamic memory */
free(a);
return 0;
}
我的上述建议是一个临时修复&我不会推荐这个,而是按照@chris Turner(http://man7.org/linux/man-pages/man3/popen.3.html)的建议使用[popen]
The
popen()function opens a process by creating a pipe, forking,
and
invoking the shell. Since a pipe is by definition unidirectional, the
type argument may specify only reading or writing, not both; the
resulting stream is correspondingly read-only or write-only.
例如
int main(void) {
char buf[1024];
FILE *fp = popen("echo Hello | base64","r");
printf("%s\n",fgets(buf,sizeof(buf),fp));
return 0;
}
