c - 如何将 system() 的结果插入字符串中?

标签 c windows

我想在字符串中插入命令 system("echo %username%"); 的结果,但我不知道如何在 C 中做到这一点。有人可以帮我吗?

最佳答案

改编自this 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!
  }
}

关于c - 如何将 system() 的结果插入字符串中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36325972/

相关文章:

c - 运行时错误 - POSIX 线程

C 用移位位交换

c++ - 使应用程序/服务试图在任务管理器中结束/终止其进程将导致 "Unable to Terminate Process"

c - 在 Windows 7 上 C 程序输出 '\a' 达到正常音量

windows - 如何让Internet Explorer在某个域自动登录

regex - 如何使用 Eclipse 或 PowerGREP 搜索和替换文件中的 block ?

windows - 此文件位于本地网络之外的位置

使用带有 Arduino 的瑞士流量计计算脉冲,它是如何完成的?

c - 如何在屏幕上显示搜索到的字符串?

arrays - char 之前的预期表达式