Share via


fread

读取流的数据。

size_t fread( 
   void *buffer,
   size_t size,
   size_t count,
   FILE *stream 
);

参数

  • buffer
    数据的存储位置。

  • size
    项目大小 (以字节为单位)。

  • count
    要读取的最大项数。

  • stream
    为 FILE 结构的指针。

返回值

fread 返回实际读取的完整项的数目,比 count 会比,如果发生错误,或者文件尾在到达的 count之前遇到*。*使用 feof 或 ferror 功能与一个文件关闭条件区分读取错误。 如果 size 或 count 为 0, fread 返回 0,并且缓冲区内容保持不变。 如果 stream 或 buffer 是 null 指针, fread 调用无效参数处理程序,如 参数验证所述。 如果执行允许继续,此功能设置 errno 到 EINVAL 并返回 0。

请参见 _doserrno、 errno、 _sys_errlist 和 _sys_nerr 有关这些内容的更多信息以及其他情况下,错误代码。

备注

fread 函数在 buffer读取到 size 字节 count 项从输入 stream 并存储它们*。*文件指针与 stream (如果有) 中实际读取的字节数增加。 如果给定流在文本模式中打开,支持返回换行符对用单个换行符替换。 替换对文件指针或返回值的效果。 ,如果发生错误,文件指针位置是不确定的。 一个部分读取的项的值无法确定的。

此功能锁定其他线程。 如果需要非固定版本,请使用 _fread_nolock。

要求

功能

必需的头

fread

stdio.h

有关其他的兼容性信息,请参见中介绍的 兼容性

示例

// crt_fread.c
// This program opens a file named FREAD.OUT and
// writes 25 characters to the file. It then tries to open
// FREAD.OUT and read in 25 characters. If the attempt succeeds,
// the program displays the number of actual items read.
 
#include <stdio.h>

int main( void )
{
   FILE *stream;
   char list[30];
   int  i, numread, numwritten;

   // Open file in text mode:
   if( fopen_s( &stream, "fread.out", "w+t" ) == 0 )
   {
      for ( i = 0; i < 25; i++ )
         list[i] = (char)('z' - i);
      // Write 25 characters to stream 
      numwritten = fwrite( list, sizeof( char ), 25, stream );
      printf( "Wrote %d items\n", numwritten );
      fclose( stream );

   }
   else
      printf( "Problem opening the file\n" );

   if( fopen_s( &stream, "fread.out", "r+t" ) == 0 )
   {
      // Attempt to read in 25 characters 
      numread = fread( list, sizeof( char ), 25, stream );
      printf( "Number of items read = %d\n", numread );
      printf( "Contents of buffer = %.25s\n", list );
      fclose( stream );
   }
   else
      printf( "File could not be opened\n" );
}
  

.NET Framework 等效项

系统:: IO:: FileStream:: 读取

请参见

参考

流I/O

fwrite

_read