fread ()- 个读取项

格式

#include <stdio.h>
size_t fread(void *buffer, size_t size, size_t count, FILE *stream);

语言级别

ANSI

线程安全

描述

fread() 函数从输入 中最多读取 count 个长度为 size 的项,并将它们存储在给定的 缓冲区中。 文件中的位置增加了读取的字节数。

返回值

fread() 函数返回成功读取的完整项数,如果发生错误,或者如果在达到 count之前满足文件结束符,那么可以小于 count 。 如果 sizecount0,那么 fread() 函数将返回零,并且数组的内容和流的状态保持不变。

errno 的值可以设置为:
含义
EGETANDPUT
写操作后发生了不允许的读操作。
ENOREC
找不到记录。
阅读
未打开该文件以执行读操作。
ERECIO
文件已打开以进行记录 I/O。
埃斯特丁
无法打开 stdin
ETRUNC
操作发生截断。
EIOERROR
发生了不可恢复的I/O错误。
EIORECERR
发生了可恢复的I/O错误。

使用 ferror()feof() 函数来区分读取错误和文件结束。

fread() 用于记录输入时,请将 size 设置为 1 ,并将 count 设置为记录的最大预期长度,以获取字节数。 如果您不知道记录长度,那么应该将 size 设置为 1 ,并将 count 设置为较大的值。 使用记录 I/O 时,一次只能读取一条记录。

示例

此示例尝试从文件 myfile中读取 NUM_ALPHA 个字符。 如果 fread()fopen()存在任何错误,那么将打印一条消息。
#include <stdio.h>
 
#define NUM_ALPHA  26
 
int main(void)
{
  FILE * stream;
  int num;       /* number of characters read from stream */
 
  /* Do not forget that the '\0' char occupies one character too! */
  char buffer[NUM_ALPHA + 1];
 
  if (( stream = fopen("mylib/myfile", "r"))!= NULL )
  {
    memset(buffer, 0, sizeof(buffer));
    num = fread( buffer, sizeof( char ), NUM_ALPHA, stream );
    if ( num ) {  /* fread success */
      printf( "Number of characters has been read = %i\n", num );
      printf( "buffer = %s\n", buffer );
      fclose( stream );
    }
    else {  /* fread failed */
      if ( ferror(stream) )    /* possibility 1 */
        perror( "Error reading myfile" );
      else if ( feof(stream))  /* possibility 2 */
        perror( "EOF found" );
    }
  }
  else
    perror( "Error opening myfile" );
 
}

相关信息