Created
June 15, 2020 05:18
-
-
Save akkuman/6e4cc4130330b261b1c2a69f68e41619 to your computer and use it in GitHub Desktop.
c语言执行命令获得返回
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <stdlib.h> | |
int exec_command(char* command, char* out); | |
int main( int argc, char *argv[] ) { | |
char *tmp_buf = malloc(1025); | |
char result[4097] = { 0 }; | |
strcpy(tmp_buf, argv[1]); | |
exec_command(tmp_buf, result); | |
printf("%s", result); | |
} | |
int exec_command(char* command, char* out) { | |
FILE *fp; | |
char buf[255] = { 0 }; | |
if ((fp = _popen(command, "r")) == NULL) { | |
perror("Fail to popen\n"); | |
exit(1); | |
} | |
while (fgets(buf, 255, fp) != NULL) { | |
strcat(out, buf); | |
} | |
_pclose(fp); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment