-1

When I read standard input to print to standard output & press ctrl+d to terminate putting in input, read() returns -1. I thought that ctrl+d meant the end of a file, and hence, would return a 0. I'm unsure as to why it is returning -1 (error). I included a snippet of my code, and if this is not enough, I will post more. Thanks for the help in advance.

for(int i = 1; i < argc; i++) {
         int filedes = open(argv[i], O_RDONLY);
          if(argv[i][0]  == '-'){
          while((n=read(0,buf,BUFFSIZE))>0){
            write(1,buf,n);
            }
          //      close(0);                                                                    
          //       close(filedes);                                                             
            }
HelpMe
  • 7
  • 1
  • 6
  • So Ctrl+D is EOF? I swear I looked everywhere trying to find this stuff before I posted this question, but I was still confused. – HelpMe Nov 01 '17 at 04:11
  • Also does this mean that the -1 EOF returns is not an error? – HelpMe Nov 01 '17 at 04:14
  • I ran it with valgrind, it returns -1 – HelpMe Nov 01 '17 at 04:17
  • 2
    And what was the value of `errno`? or the string printed by `perror()`, or returned by `strerror()`? – user207421 Nov 01 '17 at 04:17
  • @RetiredNinja `read()` returns zero at end of stream, and -1 on an error; EOF has nothing to do with it; and neither does your 'possible duplicate' link, which is about the behaviour of `getchar()`. – user207421 Nov 01 '17 at 04:21
  • @close-voters A question about `read()` is not a duplicate of a question about EOF or `getchar()`. The problem with the question is that he hasn't supplied the actual error. – user207421 Nov 02 '17 at 01:15
  • @M.M. He knows that. That's why he is expecting `read()` to return zero, instead of getting a `\04` (or `EOF`) in the read buffer. – user207421 Nov 02 '17 at 01:18
  • 1
    @M.M. I've just answered that. His code proves it. And he also said 'I thought that ctrl+d meant the end of a file', which is exactly the same as what you posted. The confusion about EOF, or rather `EOF`, was introduced by RetiredNinja, and it has been nothing but a complete waste of time. Don't add to the confusion. – user207421 Nov 02 '17 at 01:30

1 Answers1

0

Is there a reason Ctrl+D would return with an error

Yes there is a reason, but it's no good asking us what it was. Only you can discover that. You need to modify your code as follows:

while((n=read(0,buf,BUFFSIZE))>0){
    write(1,buf,n);
}
if (n < 0)
{
    perror("read");
}

and inspect the resulting error message, which will answer your question all by itself.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • @HelpMe You should consider upvoting and/or accepting answers you find useful, or else delete your question if you aren't going to clarify it further. – user207421 Nov 08 '17 at 01:26