调用fread函数,用feof和ferror来判断错误类型

man fread manual:

RETURN VALUE
       fread()  and  fwrite()  return the number of items successfully read or
       written (i.e., not the number of characters).  If an error  occurs,  or
       the  end-of-file is reached, the return value is a short item count (or
       zero).


       fread() does not distinguish between end-of-file and error, and callers
       must use feof(3) and ferror(3) to determine which occurred.       


The function feof() tests the  end-of-file  indicator  for  the  stream pointed  to by stream, returning nonzero if it is set.  The end-of-file indicator can only be cleared by the function clearerr().


       The function ferror() tests the error indicator for the stream  pointed to  by stream, returning nonzero if it is set.  The error indicator can only be reset by the clearerr() function.

feof()和ferror()无法主动检测快到文件末尾或读取出现错误;只有fread返回0或小于读取字节数的时候,用这个两个函数来区分;


while(1)

{
      bzero(stAVData, sizeof(StYaanIpcFrameHead));
      s32SendLen = fread(&stAVData, sizeof(char), sizeof(StYaanIpcFrameHead), pFd);
      if(feof(pFd) || ferror(pFd)) //来检查是否出错;
      {
          printf("Fread frame header failed!\n");
          break;
      }

}

### C语言 `fread` 函数返回值的意义及使用方法 #### 返回值意义 `fread` 函数用于从指定流中读取数据项。该函数的原型如下: ```c size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream); ``` 此函数尝试从给定的文件流 `stream` 中读取 `nmemb` 个成员,每个成员大小为 `size` 字节,并将其存储到指针 `ptr` 所指向的位置。成功执行后,它会返回实际读取的数据成员数量。 如果遇到文件结束符或发生错误,则可能不会完成全部请求的操作,在这种情况下所返回的数量将会小于预期[^1]。 对于提供的代码片段而言,当调用 `fread(buffer, sizeof(char), sizeof(buffer), p)` 后,其返回的是成功读入缓冲区中的字符数。因此,可以利用这一特性来改进上述程序逻辑以避免潜在问题。 #### 使用方法解释 为了更安全有效地使用 `fread` 检测文件结尾状态,建议采用以下方式替代原始代码中的 `while (!feof(p))` 循环结构: ```c #include <stdio.h> #include <string.h> int main() { FILE *p = fopen("a.txt", "rb"); if (p == NULL) { perror("File opening failed"); return (-1); } char buffer[4]; size_t bytesRead; while ((bytesRead = fread(buffer, 1, sizeof(buffer)-1, p)) > 0) { // Null terminate the string to prevent undefined behavior with printf. buffer[bytesRead] = '\0'; printf("buffer = %s\n", buffer); // Check for error during read operation if (ferror(p)) { fprintf(stderr, "Error reading file.\n"); fclose(p); return (-1); } // Clear any previous errors and check EOF condition properly after successful reads clearerr(p); if (feof(p)) break; } fclose(p); return 0; } ``` 这段优化后的代码通过检查每次 `fread` 的返回值来控制循环条件,而不是依赖于 `feof()` 来决定何时停止读取操作。这有助于防止因最后一次不完全读取而导致的问题,并能更好地处理文件读取过程中的各种异常情况[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值