my code is supposed to be reading in 2 files given on the command line and then printing them out to STDOUT unless a 3rd argument is given, in which case it should print to that file instead of STDOUT. I feel like everything is right but when I run the program nothing is printing out. Anything you can spot as to why not? a new set of eyes is always helpful.

int main(int ARGC, char *ARGV[]) {
   char buf1[1024];
   char buf2[1024];
   int n=0; 
   int m=0; 
   int fd=open(ARGV[1],O_RDONLY);
   int fd2=open(ARGV[2],O_RDONLY);
   int fd3=open(ARGV[3],O_WRONLY);

   do {
      int n= read(fd,buf1,sizeof(buf1));
      if(n<0) {
         perror("read error1");
      }
      if(fd3!=0) {
         write(fd3,buf1,n);
      }

      if(fd3==0) {
         write(STDOUT_FILENO,buf1,n);
      }

   } while(n==sizeof(buf1));

   do{
      int m=read(fd2,buf2,sizeof(buf2));
      if(m<0) {
         perror("read error2");
      }
      if(fd3!=0) {
         write(fd3,buf2,m);
      }
      if(fd3==0) {
         write(STDOUT_FILENO,buf2,m);
      }
   } while(m==sizeof(buf2));
}
有帮助吗?

解决方案

You are never going to write to the screen when you leave off the 3rd argument.

int fd3=open(ARGV[3],O_WRONLY); with an empty or garbage ARGV[3] will likely set fd3 to -1, which is not 0. So you will never write to STDOUT_FILENO, but instead write to an invalid file descriptor.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top