[英]How to store the system command output in a variable?
我正在执行一个 system() 函数,它返回一个文件名。 现在我不想在屏幕上显示输出(即文件名)或管道到新文件。 我只想将它存储在一个变量中。 那可能吗? 如果是这样,如何? 谢谢
"单个文件名? 是的。 这当然是可能的,但不能使用system()
。
使用popen()
。 这在c和c++ 中可用,您已经用两者标记了您的问题,但可能会用其中一个进行编码。
下面是一个 C 语言的例子:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *fpipe;
char *command = "ls";
char c = 0;
if (0 == (fpipe = (FILE*)popen(command, "r")))
{
perror("popen() failed.");
exit(EXIT_FAILURE);
}
while (fread(&c, sizeof c, 1, fpipe))
{
printf("%c", c);
}
pclose(fpipe);
return EXIT_SUCCESS;
}
您可以使用popen(3)
并从该文件中读取。
FILE *popen(const char *command, const char *type);
所以基本上你运行你的command
,然后从返回的FILE
读取。 popen(3) 就像 system(调用 shell)一样工作,所以你应该能够用它运行任何东西。
好吧,还有一种更简单的方法可以将命令输出存储在称为重定向方法的文件中。 我认为重定向很容易,它对您的情况很有用。
所以例如,这是我在 C++ 中的代码
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main(){
system("ls -l >> a.text");
return 0;
}
这里重定向标志可以轻松地将该命令的所有输出重定向到 .text 文件中。
这是我的 C++ 实现,它将system()
标准输出重定向到日志记录系统。 它使用 GNU libc 的getline()
。 如果它不能运行命令,它将抛出异常,但如果命令以非零状态运行,则不会抛出。
void infoLogger(const std::string& line); // DIY logger.
int LoggedSystem(const string& prefix, const string& cmd)
{
infoLogger(cmd);
FILE* fpipe = popen(cmd.c_str(), "r");
if (fpipe == NULL)
throw std::runtime_error(string("Can't run ") + cmd);
char* lineptr;
size_t n;
ssize_t s;
do {
lineptr = NULL;
s = getline(&lineptr, &n, fpipe);
if (s > 0 && lineptr != NULL) {
if (lineptr[s - 1] == '\n')
lineptr[--s ] = 0;
if (lineptr[s - 1] == '\r')
lineptr[--s ] = 0;
infoLogger(prefix + lineptr);
}
if (lineptr != NULL)
free(lineptr);
} while (s > 0);
int status = pclose(fpipe);
infoLogger(String::Format("Status:%d", status));
return status;
}
我同意 nitin 的观点,一种简单的方法是将其重定向到中间纯文本文件中。 这就是我正在做的事情,除了我用它来将我的服务器接收到的东西输出到一个 .txt 文件中。
它对于简单地存储加密的 UDP 数据包也非常有用,因此它们可以在以后解密。
建议使用 .txt 文件来存储 system() 函数的输出,以便它们可以等待一两秒来读取\/写入文件的应用程序,但是如果您正在执行需要立即完成的更密集的应用程序,也许可以考虑使用 popen() 将其直接通过管道传输到程序中;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.