Skip to content

Instantly share code, notes, and snippets.

@akkuman
Created June 15, 2020 05:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akkuman/6e4cc4130330b261b1c2a69f68e41619 to your computer and use it in GitHub Desktop.
Save akkuman/6e4cc4130330b261b1c2a69f68e41619 to your computer and use it in GitHub Desktop.
c语言执行命令获得返回
#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