I wrote this code for overriding the cat command in Ubuntu. The following three formats for cat instruction are working properly but rest are not working.
Working ones:
- ./catf > File.txt
- ./catf < File.txt
Not Working:
- ./catf File1.txt > File.txt
- ./catf File.txt
I am sending the terminal arguments to program as listed above. One other problem is every file also contains Enter your String: also which it shouldn’t.Here is code:
int main(int argc, char *argv[])
{
int readbytes,fp;
char buf[1024];
if(argc==1)
{
printf("Enter your String :\n\n");
readbytes=read(STDIN_FILENO,buf,1024);
write(STDOUT_FILENO,buf,readbytes);
}
else if(argc==2)
{
fp=open(argv[1],O_RDONLY);
dup2(0,fp);
close(fp);
readbytes=read(STDIN_FILENO,buf,1024);
write(STDOUT_FILENO,buf,readbytes);
}
else if(argc==3)
{
if(argv[1][0]=='<')
{
fp=open(argv[2],O_WRONLY|O_CREAT,S_IRWXU);
dup2(1,fp);
close(fp);
readbytes=read(STDIN_FILENO,buf,1024);
write(STDOUT_FILENO,buf,readbytes);
}
else if(argv[1][0]=='>')
{
fp=open(argv[2],O_RDONLY);
dup2(1,fp);
close(fp);
readbytes=read(STDIN_FILENO,buf,1024);
write(STDOUT_FILENO,buf,readbytes);
}
}
else if(argc==4)
{
printf("inside");
fp=open(argv[1],O_RDONLY);
dup2(0,fp);
close(fp);
fp=open(argv[3],O_WRONLY|O_CREAT,S_IRWXU);
dup2(1,fp);
close(fp);
readbytes=read(STDIN_FILENO,buf,1024);
printf("%c",buf);
write(STDOUT_FILENO,buf,readbytes);
}
return 0;
}
UPDATE:
I made the changes suggested by William in the code and the rest of the code is working fine but this ./catf File.txt ">" File2.txt is still not working. Why is that?
if(argc==4)
{
printf("inside4");
fp=open(argv[1],O_RDONLY);
dup2(fp,0);
close(fp);
fp=open(argv[3],O_WRONLY|O_CREAT|O_TRUNC,S_IRWXU);
dup2(fp,1);
close(fp);
readbytes=read(STDIN_FILENO,buf,1024);
//printf("%c",buf);
write(STDOUT_FILENO,buf,readbytes);
}
What is the reason for above mentioned problems?
When you invoke
cat > file1.txt,*argv[1]is not<. Rather,argcis 1 and stdout is already associated with the file by the timemainis called. If you want to pass<as an argument via the shell, you will need to quote it:Also, your invocation of
dup2has the arguments reversed;STDOUT_FILENOshould be the 2nd argument, not the first. The way you have it in yourargc==2clause is closingfpand reopening it to the original stdout.