C에서 외부 프로그램을 실행하고 출력을 구문 분석하려면 어떻게해야합니까?
게임에 필요한 파일 목록을 출력하는 유틸리티가 있습니다. C 프로그램 내에서 해당 유틸리티를 실행하고 출력을 가져와 동일한 프로그램 내에서 작업 할 수있는 방법은 무엇입니까?
업데이트 : 정보 부족에 대한 좋은 전화. 이 유틸리티는 일련의 문자열을 뱉어 내며 Mac / Windows / Linux에서 완벽하게 이식 할 수 있어야합니다. 유틸리티를 실행하고 출력 (표준 출력으로 이동)을 유지하는 프로그래밍 방식을 찾고 있습니다.
Unix-ish 환경의 간단한 문제는 popen()
.
man 페이지에서 :
popen () 함수는 파이프를 만들고 쉘을 분기하고 호출하여 프로세스를 엽니 다.
읽기 모드를 사용하는 경우 정확히 요청한 것입니다. Windows에서 구현되었는지 모르겠습니다.
더 복잡한 문제의 경우 프로세스 간 통신을 검색하려고합니다.
다른 사람들이 지적했듯이 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;
}
popen은 Windows에서 지원됩니다. 여기를 참조하십시오.
http://msdn.microsoft.com/en-us/library/96ayss4b.aspx
크로스 플랫폼을 원한다면 popen이 갈 길입니다.
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에서도 작동합니다.
This is a very generic question, you may want to include more details, like what type of output it is (just text, or a binary file?) and how you want to process it.
Edit: Hooray clarification!
Redirecting STDOUT looks to be troublesome, I've had to do it in .NET, and it gave me all sorts of headaches. It looks like the proper C way is to spawn a child process, get a file pointer, and all of a sudden my head hurts.
So heres a hack that uses temporary files. It's simple, but it should work. This will work well if speed isn't an issue (hitting the disk is slow), or if it's throw-away. If you're building an enterprise program, looking into the STDOUT redirection is probably best, using what other people recommended.
#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.
}
Make sure to check your file permissions: right now this will simply throw the file in the same directory as an exe. You might want to look into using /tmp
in nix, or C:\Users\username\Local Settings\Temp
in Vista, or C:\Documents and Settings\username\Local Settings\Temp in 2K/XP
. I think the /tmp
will work in OSX, but I've never used one.
In Linux and OS X, popen()
really is your best bet, as dmckee pointed out, since both OSs support that call. In Windows, this should help: http://msdn.microsoft.com/en-us/library/ms682499.aspx
MSDN documentation says If used in a Windows program, the _popen function returns an invalid file pointer that causes the program to stop responding indefinitely. _popen works properly in a console application. To create a Windows application that redirects input and output, see Creating a Child Process with Redirected Input and Output in the Windows SDK.
You can use system()
as in:
system("ls song > song.txt");
where ls
is the command name for listing the contents of the folder song and song
is a folder in the current directory. Resulting file song.txt
will be created in the current directory.
//execute external process and read exactly binary or text output
//can read image from Zip file for example
string run(const char* cmd){
FILE* pipe = popen(cmd, "r");
if (!pipe) return "ERROR";
char buffer[262144];
string data;
string result;
int dist=0;
int size;
//TIME_START
while(!feof(pipe)) {
size=(int)fread(buffer,1,262144, pipe); //cout<<buffer<<" size="<<size<<endl;
data.resize(data.size()+size);
memcpy(&data[dist],buffer,size);
dist+=size;
}
//TIME_PRINT_
pclose(pipe);
return data;
}
ReferenceURL : https://stackoverflow.com/questions/43116/how-can-i-run-an-external-program-from-c-and-parse-its-output
'UFO ET IT' 카테고리의 다른 글
OpenCV detectMultiScale () 매개 변수에 대한 권장 값 (0) | 2020.12.15 |
---|---|
각 비트에 대해 주어진 확률이 0 또는 1 인 의사 랜덤 비트를 생성하는 빠른 방법 (0) | 2020.12.15 |
배치 스크립트 내에서 레지스트리 키 값을 어떻게 가져올 수 있습니까? (0) | 2020.12.15 |
nohup과 데몬의 차이점은 무엇입니까? (0) | 2020.12.15 |
Python과 C ++ 통합 (0) | 2020.12.15 |