mirror of
https://github.com/RubyMetric/chsrc
synced 2025-06-08 11:14:03 +08:00
Refactor xy_getcmd()
This commit is contained in:
parent
a0f4321921
commit
fd6b9c6b9e
44
xy.h
44
xy.h
@ -435,46 +435,30 @@ xy_str_strip (const char* str)
|
|||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 执行cmd后拿到cmd的执行结果 注意从外部free掉这段内存
|
* 执行cmd,返回其最后一行输出结果
|
||||||
* 注意:执行结果后面有回车换行
|
*
|
||||||
|
* @note 返回的字符串最后面可能有换行符号
|
||||||
*/
|
*/
|
||||||
static char*
|
static char*
|
||||||
xy_getcmd(const char* cmd, bool (*func)(const char*))
|
xy_getcmd(const char* cmd, bool (*func)(const char*))
|
||||||
{
|
{
|
||||||
const int BUFSIZE = 1024;
|
const int size = 512;
|
||||||
|
char* buf = (char*) malloc(size);
|
||||||
|
|
||||||
FILE *stream;
|
FILE* stream = popen(cmd, "r");
|
||||||
char* buf = (char*)malloc(sizeof(char)*BUFSIZE);
|
|
||||||
|
|
||||||
// 执行命令,并将输出保存到 stream 指针指向的文件中。
|
|
||||||
stream = popen(cmd, "r");
|
|
||||||
if (stream == NULL) {
|
if (stream == NULL) {
|
||||||
printf("命令执行失败。\n");
|
fprintf(stderr, "命令执行失败\n");
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 从 stream 指针指向的文件中读取数据。
|
char* ret = NULL;
|
||||||
char *ret;
|
|
||||||
do {
|
while (true) {
|
||||||
if(fgets(buf, sizeof(buf), stream)==NULL)
|
if(NULL==fgets(buf, sizeof(buf), stream)) break;
|
||||||
{
|
ret = buf;
|
||||||
break;
|
if (func) { func(buf); }
|
||||||
}
|
}
|
||||||
if(func==NULL)
|
|
||||||
{
|
|
||||||
ret = buf;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
if(func(buf))
|
|
||||||
{
|
|
||||||
ret = buf;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}while(1);
|
|
||||||
|
|
||||||
// 关闭 stream 指针。
|
|
||||||
pclose (stream);
|
pclose (stream);
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user