Hello I am very new to C and am having a hard time getting this to work. Yes this is a homework assignment if anyone was wondering, but I don't think I am doing this the right way....basically what is happening is stdout is never getting set back to the display and anything i type is getting written to the out.txt file. So if i have ls > out.txt, this works fine....but if i do something like
cat test.txt.....that also gets written to out.txt and i want it to be written to the display.... here is my code thus far.....any guidance in helping me better understand this is much appreciated, along with any helpful C tips
Code:
/* a really bad approach to the parsing problem */
int i;
// scan argv for any file redirection symbols.
for (i=0; i< sizeof(argv); i++)
{
int pid;
FILE * fd;
if (argv[i] != NULL)
{
// if we encounter the symbol for output redirection execute everything infront of it with the launch app then copy its contents
// to the given name of the file.
if (strcmp( ">", argv[i] ) == 0)
{
pid = fork();
// probably not the way to do this but don't want anything including and after > to get executed with command.
argv[i] = NULL;
// open file to write to.
fd = fopen(argv[i+1],"w");
// probably not the way to do this but don't want anything including and after > to get executed with command.
argv[i+1] = NULL;
// set stdout to file
dup2(fileno(fd), fileno(stdout));\
// run the application
launch_app(argc, argv);
// copy the contents of stdout to file.
cfile(fd, stdout);
// set stdout back to normal...which doesn't work...have also tried freopen, and system(exec >/dev/tty </dev/tty)
dup2(fileno(stdout), fileno(fd));
// close the file discriptor.
fclose(fd);
// return 0 so all commands in front of > will get run by launch_app
return 1;
} // end if >
// if we encounter a symbol fo input redirection then copy the file to stdin and execute the commands infront of <
else if (strcmp( "<", argv[i] ) == 0)
{
pid = fork();
//probably not the way to do this but don't want anything including and after < to get executed with command.
argv[i] = NULL;
fd = fopen(argv[i+1], "r");
// probably not the way to do this but don't want anything including and after > to get executed with command.
argv[i+1] = NULL;
// set stdin to file
dup2(fileno(fd), fileno(stdin));
// copy the contents of the file to stdin
cfile(stdin, fd);
// launch the application
launch_app(argc, argv);
// close fd since it is now stdin
fclose(fd);
// return 0 so all commands in fron of < will get run by launch_app with stdin now as the given file
return 1;
} // end if <
else
{
system("exec >/dev/tty </dev/tty");
}
} // end if argv[i] != null
} // end for