我想在字符串中插入命令system("echo %username%");
的结果,但我不知道如何在C中执行。有人能帮我吗?
改编自这个C++解决方案,比August Karlstroms的答案更灵活一点,你可以做这样的事情:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define S_SIZE 128
char * exec(const char* cmd)
{
FILE* pipe = _popen(cmd, "r"); // open a pipe to the command
if (!pipe) return NULL; // return on Error
char buffer[S_SIZE];
int size = S_SIZE;
char * result = NULL;
while (fgets(buffer, 128, pipe) != NULL)
{
result = realloc(result, size); // allocate or reallocate memory on the heap
if (result && size != S_SIZE) // check if an error occured or if this is the first iteration
strcat(result, buffer);
else if (result)
strcpy(result, buffer); // copy in the first iteration
else
{
_pclose(pipe);
return NULL; // return since reallocation has failed!
}
size += 128;
}
_pclose(pipe);
return result; // return a pointer to the result string
}
int main(void)
{
char* result = exec("echo %username%");
if (result) // check for errors
{
printf("%s", result); // print username
free(result); // free allocated string!
}
}
使用POSIX函数popen:
#include <stdio.h>
#define LEN(arr) (sizeof (arr) / sizeof (arr)[0])
int main(void)
{
FILE *f;
char s[32];
const char *p;
f = popen("echo august", "r");
p = fgets(s, LEN(s), f);
if (p == NULL) {
s[0] = ' ';
}
pclose(f);
puts(s);
return 0;
}