Reputation: 3
This is a school assignment.
So basically I have written a C code for a shell that handles terminating the command with &
, and input / output redirection using >
or <.
using pipes and fork()
, execvp()
.
The problem is my input/output redirection only handles that for files that already exist.
What i need to know is how would I go about redirecting output to a file that doesn't exist - I know I would have to create the file, but I'm not sure how that works.
For example: ls -a < test.txt
If test.txt is not in the directory, i need to create it and redirect output to that. So how do I create this file?
here is some basic example code which does not create a new file:
else if( '>' == buff[i] ){
i++;
j=0;
if( ' ' == buff[i] )
i++;
while( ' ' != buff[i] && i < len )
out_file[j++]=buff[i++];
out_file[j]='\0';
if ( ( ofd = open(out_file,1) ) < 0 ){
perror("output redirected file");
exit( 1 );
}
close(1);
dup(ofd);
}
Any help with how I can output and create a new file would be much appreciated! Thanks!
Upvotes: 0
Views: 936
Reputation: 530922
You need to tell open
to create the file, if necessary:
if ( ( ofd = open(out_file, O_WRONLY | O_CREAT) ) < 0 ) {
Note that your code will be more readable if you use the named constants for the flags to open
. Compare with the functionally equivalent
if ( ( ofd = open(out_file, 513) ) < 0 ) {
or even
if ( ( ofd = open(out_file, 0x0201) ) < 0 ) {
Upvotes: 1