Fogest Fogest - 5 years ago 288
Bash Question

Redirecting file contents into another program in C

Making a basic shell and I need to handle file redirection. Specifically I am stumped on how I can feed data into a program like

sort
for example from a file.

Something on the command line would look like this:

$ sort < test.txt


How do I accomplish this kind of functionality in my own mini shell made in C?

I thought that maybe
sort
read from
stdin
but I guess I can't really write the contents of a file to
stdin
due to the read only aspect so I'm wondering how I actually get this data into something like
sort
for example? I am currently using forks and then using
execvp()
to execute programs.

Answer Source

You need to use freopen.

It works similarly to fopen. The first argument is the filename, the second argument is the mode, and the third argument is the file pointer to redirect. The return value is the new file pointer. So if you want to redirect stdin:

FILE *fp = freopen("input.txt", "r", stdin);

It returns a NULL pointer on failure, just like fopen.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download