Share via


fread_s

從資料流讀取資料。 此版本的 fread 具有安全性增強功能,如 CRT 中的安全性功能中所述

語法

size_t fread_s(
   void *buffer,
   size_t bufferSize,
   size_t elementSize,
   size_t count,
   FILE *stream
);

參數

buffer
資料的儲存位置。

bufferSize
以位元組為單位的目的緩衝區大小。

elementSize
以位元組為單位的讀取項目大小。

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

stream
FILE 結構的指標。

傳回值

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

如需錯誤碼的詳細資訊,請參閱 errno_doserrno_sys_errlist_sys_nerr

備註

fread_s 函式會從輸入 stream 讀取 elementSize 個位元組的 count 個項目,並將其儲存在 buffer。 與 stream 相關聯的檔案指標(如果有的話)會依讀取的位元組 fread_s 數目進階。 如果指定的資料流程以文字模式開啟,則歸位字元換行字元會取代歸位字元。 這種取代不會影響檔案指標或傳回值。 發生錯誤時,無法確定檔案指標位置。 無法判斷部分讀取專案的值。

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

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

需求

函式 必要的標頭
fread_s <stdio.h>

如需相容性詳細資訊,請參閱相容性

範例

// crt_fread_s.c
// Command line: cl /EHsc /nologo /W4 crt_fread_s.c
//
// This program opens a file that's named FREAD.OUT and
// writes characters to the file. It then tries to open
// FREAD.OUT and read in characters by using fread_s. If the attempt succeeds,
// the program displays the number of actual items read.

#include <stdio.h>

#define BUFFERSIZE 30
#define DATASIZE 22
#define ELEMENTCOUNT 2
#define ELEMENTSIZE (DATASIZE/ELEMENTCOUNT)
#define FILENAME "FREAD.OUT"

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

   for ( i = 0; i < DATASIZE; i++ )
      list[i] = (char)('z' - i);
   list[DATASIZE] = '\0'; // terminal null so we can print it

   // Open file in text mode:
   if( fopen_s( &stream, FILENAME, "w+t" ) == 0 )
   {
      // Write DATASIZE characters to stream
      printf( "Contents of buffer before write/read:\n\t%s\n\n", list );
      numwritten = fwrite( list, sizeof( char ), DATASIZE, stream );
      printf( "Wrote %d items\n\n", numwritten );
      fclose( stream );
   } else {
      printf( "Problem opening the file\n" );
      return -1;
   }

   if( fopen_s( &stream, FILENAME, "r+t" ) == 0 )   {
      // Attempt to read in characters in 2 blocks of 11
      numread = fread_s( list, BUFFERSIZE, ELEMENTSIZE, ELEMENTCOUNT, stream );
      printf( "Number of %d-byte elements read = %d\n\n", ELEMENTSIZE, numread );
      printf( "Contents of buffer after write/read:\n\t%s\n", list );
      fclose( stream );
   } else {
      printf( "File could not be opened\n" );
      return -1;
   }
}
Contents of buffer before write/read:
        zyxwvutsrqponmlkjihgfe

Wrote 22 items

Number of 11-byte elements read = 2

Contents of buffer after write/read:
        zyxwvutsrqponmlkjihgfe

另請參閱

資料流 I/O
fwrite
_read