如果要在函数中改变指针内存大小,请参考一下代码:
// 执行命令并返回输出信息
int systemex(char *cmd, char **output)
{ // 执行命令,并返回输出结果
FILE *pipe;
int Result = -1, TotalSize = 0, ReadSize = 0;
char buf[1024] = {0};
*output[0] = 0;
pipe = popen(cmd, "r");
Result = errno;
while (!feof(pipe)) {
memset(buf, 0, sizeof(buf));
ReadSize = fread(buf, 1, sizeof(buf) - 1, pipe);
if (ReadSize > 0) {
TotalSize += ReadSize;
*output = realloc(*output, TotalSize);
strcat(*output, buf);
}
}
printf("Size: %d\n, Error: %d", TotalSize, Result);
fclose(pipe);
return Result;
}
调用的时候:
char *out = malloc(1024);
systemex("ls / -l", &out);