Issue
I am trying to read from a file and print it for the user to read. My task is similar to the UNIX 'cat' command but my code does not print anything.
#include<unistd.h>
#include<fcntl.h>
#include<stdio.h> //for printf
int main(int argc, char *argv[])
{
int fd;
char buffer;
if(argc==1)
fd=open(argv[1],O_RDONLY);
else
if (fd=open(argv[1],O_RDONLY) ==0){
printf("Error opening");
return(0);
}
while((read(fd,&buffer,1)) != -1){
read(fd,&buffer,1);
write(STDOUT_FILENO,buffer, 1);
}
return(0);
}
Solution
You're reading from the wrong FD due to a precedence issue. if (fd=open(argv[1],O_RDONLY) ==0)
is parsed as if (fd=(open(argv[1],O_RDONLY) ==0))
. You wanted it to be parsed as if ((fd=open(argv[1],O_RDONLY)) ==0)
instead, so write that.
Other problems:
0
is a legitimate FD. You should check against-1
instead to see ifopen
failed.- If
argc
is 1, thenargv[1]
is a null pointer, which you shouldn't try toopen
. - Calling
read
twice in a row instead of just once means you're going to throw away every other character. write
expects a pointer, so pass it&buffer
too like you do withread
. Remember it's notprintf
.read
can return 0 when you get to EOF, and right now that will send your program into an infinite loop printing the final character.
Answered By - Joseph Sible-Reinstate Monica