[英]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.