Task 4: Input/Output Redirection Your shell must support I/O redirection. If an
ID: 3852736 • Letter: T
Question
Task 4: Input/Output Redirection
Your shell must support I/O redirection. If an external command is followed by "<", it must read input from the
named file. For example, the command line "sort < foo" means that sort should be fed the file foo via stdin. If
an external command is followed by a ">", your shell must arrange it so that stdout of the command is
directed to a file. For example, "ls > save" means that the ls command should save its output to the file named
"save". You could have both on the same command, for example: "sort < infile > outfile".
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <readline/readline.h>
#include<string.h>
#include <readline/history.h>
#include <limits.h>
/* Simple example of using gnu readline to get lines of input from a user.
Needs to be linked with -lreadline -lcurses
add_history tells the readline library to add the line to it's
internal history, so that using up-arrow (or ^p) will allows the user
to see/edit previous lines.
*/
int main(int argc, char **argv) {
char *s;
while (s=readline("prompt> ")) {
add_history(s); /* adds the line to the readline history buffer */
if((strcmp(s,"pwd"))==0)//Check if input is pwd
{
char* cwd;
char buff[PATH_MAX + 1];
cwd = getcwd( buff, PATH_MAX + 1 );
printf( "Directory is %s. ", cwd );//Print the directory if input is pwd
}
else if((strcmp(s,"exit"))==0)//Check if input is exit
{
exit(0);//Exit
}
else if(s[0]='c'&& s[1]=='d')//Check if first two letters of input is c and d
{
char a[50],b[3];
sscanf(s,"%s %s",b,a);//Scanf the directory in a
chdir(a);//Change directory to a
}
free(s); /* clean up! */
}
return(0);}
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <readline/readline.h>
#include<string.h>
#include <readline/history.h>
#include <limits.h>
int main(int argc, char **argv) {
char *s;
while (s=readline("prompt> ")) {
add_history(s); /* adds the line to the readline history buffer */
if((strcmp(s,"pwd"))==0)//Check if input is pwd
{
char* cwd;
char buff[PATH_MAX + 1];
cwd = getcwd( buff, PATH_MAX + 1 );
printf( "Directory is %s. ", cwd );//Print the directory if input is pwd
}
else if((strcmp(s,"exit"))==0)//Check if input is exit
{
exit(0);//Exit
}
else if(s[0]='c'&& s[1]=='d')//Check if first two letters of input is c and d
{
char a[50],b[3];
sscanf(s,"%s %s",b,a);//Scanf the directory in a
chdir(a);//Change directory to a
}
free(s); /* clean up! */
}
return(0);}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.