fread

從資料流讀取資料。

語法

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

參數

buffer
資料的儲存位置。

size
項目大小 (位元組)。

count
要讀取項目的最大數量。

stream
FILE 結構的指標。

傳回值

fread會傳回函式讀取的完整專案數目,如果發生錯誤,或到達 之前 count 遇到檔案結尾,則它可能小於 count 。 使用 feofferror 函式,來區分讀取錯誤與檔案結尾條件。 如果 sizecount 是 0,fread 會傳回 0,而且緩衝區內容未變更。 如果 streambuffer 為 Null 指標, fread 請叫用不正確參數處理常式,如參數驗證 中所述 。 若允許繼續執行,此函式會將 errno 設為 EINVAL,並傳回 0。

如需傳回碼的詳細資訊,請參閱 errno_doserrno_sys_errlist_sys_nerr

備註

fread 函式會從輸入 stream 讀取 size 個位元組的 count 個項目,並將其儲存在 buffer。 與 stream 相關聯的檔案指標(如果有的話),會依讀取的位元組 fread 數目進階。 如果指定的資料流程以 文字模式 開啟,Windows 樣式的新行會轉換成 Unix 樣式分行符號。 也就是說,歸位字元換行字元 (CRLF) 配對會由單行摘要 (LF) 字元取代。 這種取代不會影響檔案指標或傳回值。 發生錯誤時,無法確定檔案指標位置。 無法判斷部分讀取專案的值。

在文字模式資料流程上使用時,如果所要求的資料量(也就是 size * count ) 大於或等於內部 FILE * 緩衝區大小(根據預設,大小為 4096 位元組,可使用 setvbuf 設定),資料流程資料會直接複製到使用者提供的緩衝區,而且會在該緩衝區中完成換行轉換。 由於轉換的資料可能比複製到緩衝區的資料流程資料短,因此過去 buffer [ return_valuesize * ] 的資料(其中 return_value 是 來自 的傳回值 fread )可能包含來自檔案的未轉換資料。 基於這個理由,如果緩衝區的意圖是做為 C 樣式字串,建議您在 [ return_value * size ] 上 buffer 以 Null 終止字元資料。 如需文字模式和二進位模式效果的詳細資訊,請參閱 fopen

此函式會鎖定其他執行緒。 如果您需要非鎖定版本,請使用 _fread_nolock

根據預設,此函式的全域狀態會限定于應用程式。 若要變更此行為,請參閱 CRT 中的全域狀態。

需求

函式 必要的標頭
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" );
}
Wrote 25 items
Number of items read = 25
Contents of buffer = zyxwvutsrqponmlkjihgfedcb

另請參閱

資料流 I/O
文字和二進位模式檔案 I/O
fopen
fwrite
_read