好吧,假设您在 Windows 环境中使用命令行,您可以使用管道或命令行重定向。例如,
commandThatOutputs.exe > someFileToStoreResults.txt
或
commandThatOutputs.exe | yourProgramToProcessInput.exe
在您的程序中,您可以使用 C 标准输入函数来读取其他程序输出(scanf 等):http://irc.essex.ac.uk/www.iota-six.co.uk/c/c1_standard_input_and_output.asp。您也可以使用文件示例并使用 fscanf。这也应该适用于 Unix/Linux。
这是一个非常笼统的问题,您可能希望包含更多详细信息,例如它是什么类型的输出(只是文本,还是二进制文件?)以及您希望如何处理它。
编辑:万岁澄清!
重定向 STDOUT 看起来很麻烦,我不得不在 .NET 中进行,这让我很头疼。看起来正确的 C 方法是生成一个子进程,获取一个文件指针,突然间我的头疼了。
所以这里有一个使用临时文件的 hack。这很简单,但它应该工作。如果速度不是问题(撞击磁盘很慢),或者它被丢弃,这将很有效。如果您正在构建企业程序,最好使用其他人推荐的方法来研究 STDOUT 重定向。
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
FILE * fptr; // file holder
char c; // char buffer
system("dir >> temp.txt"); // call dir and put it's contents in a temp using redirects.
fptr = fopen("temp.txt", "r"); // open said file for reading.
// oh, and check for fptr being NULL.
while(1){
c = fgetc(fptr);
if(c!= EOF)
printf("%c", c); // do what you need to.
else
break; // exit when you hit the end of the file.
}
fclose(fptr); // don't call this is fptr is NULL.
remove("temp.txt"); // clean up
getchar(); // stop so I can see if it worked.
}
确保检查您的文件权限:现在这只会将文件与 exe 放在同一目录中。您可能想考虑在 nix 中使用 /tmp,或在 Vista 中使用 C:\Users\username\Local Settings\Temp,或 C:\Documents and Settings\username\Local Settings\Temp in 2K/XP。我认为/tmp 可以在 OSX 中使用,但我从未使用过。