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

前端 未结 3 1368
眼角桃花
眼角桃花 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:24

    You can check it with ferror(3), right after the while:

    while (EOF != (ch = fgetc(fp)))
       // do something
    
    if (ferror(fp) != 0)
       // error handling
    

    ferror returns a non-zero if an error occured.

    If you want use fp after an error occured, you'll need to clear the error flag with clearerr:

    clearerr(fp);
    

提交回复
热议问题