Jos*_*ews 59 c external-process
我有一个实用程序可以输出游戏所需的文件列表.如何在C程序中运行该实用程序并获取其输出,以便我可以在同一程序中对其执行操作?
更新:很好地呼吁缺乏信息.该实用程序吐出一系列字符串,这应该是完全可移植的Mac/Windows/Linux.请注意,我正在寻找一种程序化的方法来执行该实用程序并保留其输出(转到stdout).
Mes*_*ion 55
正如其他人所指出的那样,popen()
是最标准的方式.由于没有回答提供了使用此方法的示例,因此在这里:
#include <stdio.h>
#define BUFSIZE 128
int parse_output(void) {
char *cmd = "ls -l";
char buf[BUFSIZE];
FILE *fp;
if ((fp = popen(cmd, "r")) == NULL) {
printf("Error opening pipe!\n");
return -1;
}
while (fgets(buf, BUFSIZE, fp) != NULL) {
// Do whatever you want here...
printf("OUTPUT: %s", buf);
}
if(pclose(fp)) {
printf("Command not found or exited with error status\n");
return -1;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
好吧,假设您在Windows环境中使用命令行,则可以使用管道或命令行重定向.例如,
commandThatOutputs.exe > someFileToStoreResults.txt
Run Code Online (Sandbox Code Playgroud)
要么
commandThatOutputs.exe | yourProgramToProcessInput.exe
Run Code Online (Sandbox Code Playgroud)
在程序中,您可以使用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方式是生成一个子进程,获取一个文件指针,突然我的头疼.
所以这是一个使用临时文件的黑客.这很简单,但应该有效.如果速度不是问题(击中磁盘很慢),或者如果它丢失,这将很好地工作.如果您正在构建企业程序,那么使用其他人推荐的方法查看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.
}
Run Code Online (Sandbox Code Playgroud)
确保检查文件权限:现在这只是将文件放在与exe相同的目录中.您可能希望了解/tmp
在nix中使用,或C:\Users\username\Local Settings\Temp
在Vista中使用或C:\Documents and Settings\username\Local Settings\Temp in 2K/XP
.我认为/tmp
它将在OSX中运行,但我从未使用过.
归档时间: |
|
查看次数: |
62478 次 |
最近记录: |