<p>I've got a utility that outputs a list of files required by a game.  How can I run that utility within a C program and grab its output so I can act on it within the same program?</p>
<p>UPDATE: Good call on the lack of information.  The utility spits out a series of strings, and this is supposed to be portable across Mac/Windows/Linux.  Please note, I'm looking for a programmatic way to execute the utility and retain its output (which goes to stdout).</p>

[{'answer_id': 43120, 'author': 'dmckee --- ex-moderator kitten', 'author_id': 2509, 'author_profile': 'https://Stackoverflow.com/users/2509', 'pm_score': 7, 'selected': True, 'text': '<p>For simple problems in Unix-ish environments try <a href="http://pubs.opengroup.org/onlinepubs/009696799/functions/popen.html" rel="noreferrer"><code>popen()</code></a>. </p>\n\n<p>From the man page:</p>\n\n<blockquote>\n  <p>The popen() function opens a process by creating a pipe, forking and invoking the shell.</p>\n</blockquote>\n\n<p>If you use the read mode this is exactly what you asked for. I don\'t know if it is implemented in Windows.</p>\n\n<p>For more complicated problems you want to look up inter-process communication.</p>\n'}, {'answer_id': 43122, 'author': 'David J. Sokol', 'author_id': 1390, 'author_profile': 'https://Stackoverflow.com/users/1390', 'pm_score': 3, 'selected': False, 'text': '<p>Well, assuming you\'re on a command line in a windows environment, you can use pipes or command line redirects.  For instance,</p>\n\n<pre><code>commandThatOutputs.exe &gt; someFileToStoreResults.txt\n</code></pre>\n\n<p>or</p>\n\n<pre><code>commandThatOutputs.exe | yourProgramToProcessInput.exe\n</code></pre>\n\n<p>Within your program, you could use the C standard input functions to read the other programs output (scanf, etc.):  <a href="http://irc.essex.ac.uk/www.iota-six.co.uk/c/c1_standard_input_and_output.asp" rel="noreferrer">http://irc.essex.ac.uk/www.iota-six.co.uk/c/c1_standard_input_and_output.asp</a> .  You could also use the file example and use fscanf.  This should also work in Unix/Linux.</p>\n\n<p>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.</p>\n\n<p>Edit:  Hooray clarification!</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<pre><code>#include &lt;stdlib.h&gt;\n#include &lt;stdio.h&gt;\n\nint main(int argc, char* argv[])\n{\n    FILE * fptr;                    // file holder\n    char c;                         // char buffer\n\n\n    system("dir &gt;&gt; temp.txt");      // call dir and put it\'s contents in a temp using redirects.\n    fptr = fopen("temp.txt", "r");  // open said file for reading.\n                                    // oh, and check for fptr being NULL.\n    while(1){\n        c = fgetc(fptr);\n        if(c!= EOF)\n            printf("%c", c);        // do what you need to.\n        else\n            break;                  // exit when you hit the end of the file.\n    }\n    fclose(fptr);                   // don\'t call this is fptr is NULL.  \n    remove("temp.txt");             // clean up\n\n    getchar();                      // stop so I can see if it worked.\n}\n</code></pre>\n\n<p>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 <code>/tmp</code> in nix, or <code>C:\\Users\\username\\Local Settings\\Temp</code> in Vista, or <code>C:\\Documents and Settings\\username\\Local Settings\\Temp in 2K/XP</code>.  I think the <code>/tmp</code> will work in OSX, but I\'ve never used one.</p>\n'}, {'answer_id': 43136, 'author': 'Arktronic', 'author_id': 4479, 'author_profile': 'https://Stackoverflow.com/users/4479', 'pm_score': 2, 'selected': False, 'text': '<p>In Linux and OS X, <code>popen()</code> really is your best bet, as dmckee pointed out, since both OSs support that call. In Windows, this should help: <a href="http://msdn.microsoft.com/en-us/library/ms682499.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms682499.aspx</a></p>\n'}, {'answer_id': 53372, 'author': 'Adam Pierce', 'author_id': 5324, 'author_profile': 'https://Stackoverflow.com/users/5324', 'pm_score': 4, 'selected': False, 'text': '<p>popen is supported on Windows, see here:</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/96ayss4b.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/96ayss4b.aspx</a></p>\n\n<p>If you want it to be cross-platform, popen is the way to go.</p>\n'}, {'answer_id': 2823210, 'author': 'Angus Connell', 'author_id': 246659, 'author_profile': 'https://Stackoverflow.com/users/246659', 'pm_score': 2, 'selected': False, 'text': '<p>MSDN documentation says\nIf 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.</p>\n'}, {'answer_id': 17651740, 'author': 'dharmabook.ru', 'author_id': 2583079, 'author_profile': 'https://Stackoverflow.com/users/2583079', 'pm_score': -1, 'selected': False, 'text': '<pre><code>//execute external process and read exactly binary or text output\n//can read image from Zip file for example\nstring run(const char* cmd){\n    FILE* pipe = popen(cmd, "r");\n    if (!pipe) return "ERROR";\n    char buffer[262144];\n    string data;\n    string result;\n    int dist=0;\n    int size;\n    //TIME_START\n    while(!feof(pipe)) {\n        size=(int)fread(buffer,1,262144, pipe); //cout&lt;&lt;buffer&lt;&lt;" size="&lt;&lt;size&lt;&lt;endl;\n        data.resize(data.size()+size);\n        memcpy(&amp;data[dist],buffer,size);\n        dist+=size;\n    }\n    //TIME_PRINT_\n    pclose(pipe);\n    return data;\n}\n</code></pre>\n'}, {'answer_id': 19907372, 'author': 'Prabhat Kumar Singh', 'author_id': 2608019, 'author_profile': 'https://Stackoverflow.com/users/2608019', 'pm_score': 1, 'selected': False, 'text': '<p>You can use <code>system()</code> as in:</p>\n\n<pre><code>system("ls song &gt; song.txt");\n</code></pre>\n\n<p>where <code>ls</code> is the command name for listing the contents of the folder song and <code>song</code> is a folder in the current directory.  Resulting file <code>song.txt</code> will be created in the current directory.</p>\n'}, {'answer_id': 28971647, 'author': 'MestreLion', 'author_id': 624066, 'author_profile': 'https://Stackoverflow.com/users/624066', 'pm_score': 6, 'selected': False, 'text': '<p>As others have pointed out, <code>popen()</code> is the most standard way.  And since no answer provided an example using this method, here it goes:</p>\n<pre><code>#include &lt;stdio.h&gt;\n\n#define BUFSIZE 128\n\nint parse_output(void) {\n    char *cmd = &quot;ls -l&quot;;    \n    \n    char buf[BUFSIZE];\n    FILE *fp;\n\n    if ((fp = popen(cmd, &quot;r&quot;)) == NULL) {\n        printf(&quot;Error opening pipe!\\n&quot;);\n        return -1;\n    }\n\n    while (fgets(buf, BUFSIZE, fp) != NULL) {\n        // Do whatever you want here...\n        printf(&quot;OUTPUT: %s&quot;, buf);\n    }\n\n    if (pclose(fp)) {\n        printf(&quot;Command not found or exited with error status\\n&quot;);\n        return -1;\n    }\n\n    return 0;\n}\n</code></pre>\n<p>Sample output:</p>\n<pre><code>OUTPUT: total 16\nOUTPUT: -rwxr-xr-x 1 14077 14077 8832 Oct 19 04:32 a.out\nOUTPUT: -rw-r--r-- 1 14077 14077 1549 Oct 19 04:32 main.c\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/43116', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3830/']