简体   繁体   中英

Redirect command output to file in C

I am trying to redirect output of ls command to a file fout.txt But file fout.txt contains only Here is the output

Below is my program:

int fout, ferr;
char *tok[3];
tok[0] = "ls", tok[1] = ">", tok[2] = "fout.txt";
fout = open("fout.txt", O_RDWR|O_CREAT|O_APPEND, 0600);
ferr = open("ferr.txt", O_RDWR|O_CREAT|O_APPEND, 0600);
puts("Here is the output\n");
execvp(tok[0], tok);
close(fout);
close(ferr);

Please help here.

Redirection such as you are attempting is not done directly via execvp() call. It's done in bash like this :

/* Execute a simple command that is hopefully defined in a disk file
   somewhere.

   1) fork ()
   2) connect pipes
   3) look up the command
   4) do redirections
   5) execve ()
   6) If the execve failed, see if the file has executable mode set.
   If so, and it isn't a directory, then execute its contents as
   a shell script.

   Note that the filename hashing stuff has to take place up here,
   in the parent.  This is probably why the Bourne style shells
   don't handle it, since that would require them to go through
   this gnarly hair, for no good reason.

Note the "connect pipes".

(This is not meant to be a complete answer - the questioner should be required to research something ...)

The different redirections characters ( < > >> | )are interpreted by the shells. As you ask a direct execvp execution, you just execute ls command with parameters > and fout.txt .

When I do that I get on stderr:

ls: >: No such file or directory
ls: fout.txt: No such file or directory

To redirect with the exec family of function you must explicitely open the files and use dup2 to connect them to stdin (0), stdout(1) and/or stderr(2) as shown in In C how do you redirect stdin/stdout/stderr to files when making an execvp() or similar call?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM