实现 xy_run_capture()

[GitHub #268 #269]
This commit is contained in:
Aoran Zeng 2025-08-20 19:49:01 +08:00
parent 98516e0f4d
commit f195709493
No known key found for this signature in database
GPG Key ID: 8F8BA8488E10ED98
2 changed files with 39 additions and 1 deletions

View File

@ -815,6 +815,44 @@ xy_run (const char *cmd, unsigned long n)
}
/**
* @brief
*
* @param[in] cmd
* @param[out] output
*
* @return
*/
static int
xy_run_capture (const char *cmd, char **output)
{
int cap = 8192; /* 假如1行100个字符大约支持80行输出 */
char *buf = (char *) xy_malloc0 (cap);
FILE *stream = popen (cmd, "r");
if (stream == NULL)
{
fprintf (stderr, "xy: 命令执行失败\n");
return -1;
}
int size = 0;
size_t n;
while ((n = fread (buf + size, 1, cap - size, stream)) > 0) {
size += n;
if (size == cap)
{
cap *= 2;
char *new_buf = realloc (buf, cap);
buf = new_buf;
}
}
buf[size] = '\0';
int status = pclose (stream);
*output = buf;
return status;
}
/******************************************************

View File

@ -28,7 +28,7 @@ print_str_for_map (const char *key, void *value)
int
main (int argc, char const *argv[])
{
xy_useutf8 ();
xy_use_utf8 ();
println (xy_os_depend_str ("Hello, Windows!", "Hello, Unix!"));