共用方式為


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為止。 使用feof或ferror函式來區分檔案結尾狀況和錯誤。 如果size或count為 0, fread_s會傳回 0 緩衝區內容並不會改變。 如果stream或buffer是空值的指標, fread_s中所述,將不正確的參數處理常式中,會叫用參數驗證。 如果執行,則允許繼續執行,這個函式會將errno到EINVAL ,並傳回 0。

如需有關錯誤碼的詳細資訊,請參閱 _doserrno、 errno、 _sys_errlist,以及 _sys_nerr

備註

fread_s函式會讀取最多count的項目elementSize個輸入位元組stream ,並將其儲存到在buffer。 檔案指標與其相關聯stream (如果有的話) 會遞增的實際讀取的位元組數目。 在文字模式開啟指定的資料流時,輸入鍵符號作為 return–linefeed 組所取代單一的換行字元。 取代已經不會影響檔案指標或傳回值。 檔案指標位置是不確定如果發生錯誤。 無法判定部分讀取的項目值。

這個函式是由其他執行緒鎖定。 如果您需要的非鎖定版本,使用_fread_nolock。

需求

Function

所需標頭

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;
   }
}
  
  
  
  
  
  

請參閱

參考

資料流 I/O

fwrite

_read