fgetc(): Is it enough to just check EOF?

前端 未结 3 1369
眼角桃花
眼角桃花 2020-12-07 01:59

In various examples found on the web fgetc() is used like this:

FILE *fp = fopen(PATH, \"r\");

if (fp == NULL) {
    perror(\"main\");
    exit         


        
3条回答
  •  感动是毒
    2020-12-07 02:15

    Looping until fgetc returns EOF is perfectly fine. Afterwards, if you want to know whether the loop ended due to simply reaching the end of the file or due to an error, you should call ferror or feof. If you don't care you can skip the call.

    Note that it matters whether you check feof or ferror, because the error indicator for a stream is sticky and can evaluate true even when hitting eof was the cause of fgetc failure. Normally you should use feof to check, and if it returns false, conclude that the loop stopped due to a new error.

提交回复
热议问题