code_junkie

How can I run an external program from C and parse its output?

Nov 10th, 2011
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1. The popen() function opens a process by creating a pipe, forking and involking the
  2. shell.
  3.  
  4. commandThatOutputs.exe > someFileToStoreResults.txt
  5.  
  6. commandThatOutputs.exe | yourProgramToProcessInput.exe
  7.  
  8. #include <stdlib.h>
  9. #include <stdio.h>
  10.  
  11. int main(int argc, char* argv[])
  12. {
  13. FILE * fptr; // file holder
  14. char c; // char buffer
  15.  
  16.  
  17. system("dir >> temp.txt"); // call dir and put it's contents in a temp using redirects.
  18. fptr = fopen("temp.txt", "r"); // open said file for reading.
  19. // oh, and check for fptr being NULL.
  20. while(1){
  21. c = fgetc(fptr);
  22. if(c!= EOF)
  23. printf("%c", c); // do what you need to.
  24. else
  25. break; // exit when you hit the end of the file.
  26. }
  27. fclose(fptr); // don't call this is fptr is NULL.
  28. remove("temp.txt"); // clean up
  29.  
  30. getchar(); // stop so I can see if it worked.
  31. }
Add Comment
Please, Sign In to add comment