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?
UPDATE: Good call on the lack of information. The utility spits out a series of strings, and this is supposed to be complete 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).
Well, assuming you're on a command line in a windows environment, you can use pipes or command line redirects. For instance,
or
Within your program, you could use the C standard input functions to read the other programs output (scanf, etc.): http://irc.essex.ac.uk/www.iota-six.co.uk/c/c1_standard_input_and_output.asp . You could also use the file example and use fscanf. This should also work in 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.
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, orC:\Users\username\Local Settings\Temp
in Vista, orC:\Documents and Settings\username\Local Settings\Temp in 2K/XP
. I think the/tmp
will work in OSX, but I've never used one.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:where
ls
is the command name for listing the contents of the folder song andsong
is a folder in the current directory. Resulting filesong.txt
will be created in the current directory.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.aspxAs others have pointed out,
popen()
is the most standard way. And since no answer provided an example using this method, here it goes: