0

I have the following code:

int copynFile(FILE * origin, FILE * destination, int nBytes) {
    for(int i = 0; i < nBytes; i++){
        if(feof(origin)!=0) return i;
        int byte = getc(origin);
        if(byte == EOF || putc(byte, destination)==EOF) return -1;
    }
    return nBytes;
}

My intention is that this function should copy nbytes from origin to destination. If the number of bytes in origin is less than nBytes, it shoudl return how many bytes have been actually copied to destination, and return -1 if a mistake happens.

Now, I added the return -1 line as something that should only happen in excepcional circumstances, but it is triggering every time the function reaches the EOF of origin!

Thus i believe that the if(feof(origin)!=0) return i; is not doing its job of detecting the end of file. What is the problem?

Jsevillamol
  • 2,425
  • 2
  • 23
  • 46
  • 2
    `feof` does not detect you are at end of file. It returns `true` after you *already read past the end of the file*. Similar question is [Why is “while ( !feof (file) )” always wrong?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) It is not even necessary, because of the test `if(byte == EOF ...` – Weather Vane Oct 14 '17 at 17:54
  • I think you'll find what you need here: https://stackoverflow.com/questions/1835986/how-to-use-eof-to-run-through-a-text-file-in-c – Nik Oct 14 '17 at 17:55

0 Answers0