Filehandle issue with system call in C
In my C program I make a system call that executes the 'cat' UNIX command, something like this.
sprintf(command, "cat %s", filename);
fprintf(stderr, "Executing command: '%s'\n", command);
system(command);
When I compile and run the program, the command is not executed properly. instead I get the following error.
Executing command: 'cat temp.txt'
cat: stdout: Bad file descriptor
My question is two-fold.
- Why is this code not working correctly, and how can I fix it?
- When I try something like
perl -e 'system("cat temp.txt")'
on the command line, it works as expected. What is the difference between how Perl deals with file handles and how C deals with them?
Thanks!
Update: Thanks to the comments, I figured out the problem pretty q开发者_运维技巧uickly. I had accidentally closed stdout earlier in the program, which is why there was an error when the cat
program tried to print to stdout. So it looks like there is no difference between how C and Perl deal with file handles: the following command generates the exact same error.
$ perl -e 'close(STDOUT); system("cat temp.txt")'
cat: stdout: Bad file descriptor
Seems like your default stdout
file descriptor is not there. stdout
is closed.
精彩评论