简体   繁体   中英

Why am I not getting an output when reading from a file descriptor?

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);
}

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 if open failed.
  • If argc is 1, then argv[1] is a null pointer, which you shouldn't try to open .
  • 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 with read . Remember it's not printf .
  • 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM