fscanf, _fscanf_l, fwscanf, _fwscanf_l

從資料流讀取格式化資料。 這些函式有更安全的版本可供使用;請參閱 、、 fwscanf_s_fscanf_s_l_fwscanf_s_lfscanf_s

語法

int fscanf(
   FILE *stream,
   const char *format [,
   argument ]...
);
int _fscanf_l(
   FILE *stream,
   const char *format,
   _locale_t locale [,
   argument ]...
);
int fwscanf(
   FILE *stream,
   const wchar_t *format [,
   argument ]...
);
int _fwscanf_l(
   FILE *stream,
   const wchar_t *format,
   _locale_t locale [,
   argument ]...
);

參數

stream
FILE 結構的指標。

format
格式控制字串。

argument
選擇性引數。

locale
要使用的地區設定。

傳回值

每個函式都會傳回成功轉換和指派的欄位數目;傳回值不包含已讀取但未指派的欄位。 傳回值 0 表示未指派任何欄位。 如果發生錯誤,或進行第一次轉換之前就到達檔案資料流結尾,則 fscanffwscanf 的傳回值是 EOF

這些函式會驗證它們的參數。 如果 streamformatNULL 指標,則會叫用不正確參數處理常式,如參數驗證 中所述 。 如果允許繼續執行,這些函式會傳回 EOF,並將 errno 設為 EINVAL

備註

fscanf 函式會將 stream 之目前位置的資料讀取到 argument (如果有的話) 所指定的位置。 每個 argument 必須是 format 中對應至型別指定名稱的型別變數指標。 format控制輸入欄位的解譯,並且具有與 formatscanf 變數相同的形式和函式;如需 的描述 format ,請參閱 scanf

fwscanffscanf 的寬字元版本;fwscanf 的格式引數是寬字元字串。 如果資料流是以 ANSI 模式開啟,則這些函式的行為相同。 fscanf 目前不支援來自 UNICODE 資料流的輸入。

這些有 _l 尾碼的函式版本是一樣的,不同之處在於會使用傳入的地區設定,而不使用目前的執行緒地區設定。

泛型文字常式對應

TCHAR.H 常規 _UNICODE_MBCS 未定義 _MBCS 定義 _UNICODE 定義
_ftscanf fscanf fscanf fwscanf
_ftscanf_l _fscanf_l _fscanf_l _fwscanf_l

如需詳細資訊,請參閱 格式化規格欄位: scanfwscanf 函式

需求

函式 必要的標頭
fscanf, _fscanf_l <stdio.h>
fwscanf, _fwscanf_l <stdio.h><wchar.h>

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

範例

// crt_fscanf.c
// compile with: /W3
// This program writes formatted
// data to a file. It then uses fscanf to
// read the various data back from the file.

#include <stdio.h>

FILE *stream;

int main( void )
{
   long l;
   float fp;
   char s[81];
   char c;

   if( fopen_s( &stream, "fscanf.out", "w+" ) != 0 )
      printf( "The file fscanf.out was not opened\n" );
   else
   {
      fprintf( stream, "%s %ld %f%c", "a-string",
               65000, 3.14159, 'x' );
      // Security caution!
      // Beware loading data from a file without confirming its size,
      // as it may lead to a buffer overrun situation.

      // Set pointer to beginning of file:
      fseek( stream, 0L, SEEK_SET );

      // Read data back from file:
      fscanf( stream, "%s", s );   // C4996
      fscanf( stream, "%ld", &l ); // C4996

      fscanf( stream, "%f", &fp ); // C4996
      fscanf( stream, "%c", &c );  // C4996
      // Note: fscanf is deprecated; consider using fscanf_s instead

      // Output data read:
      printf( "%s\n", s );
      printf( "%ld\n", l );
      printf( "%f\n", fp );
      printf( "%c\n", c );

      fclose( stream );
   }
}
a-string
65000
3.141590
x

另請參閱

資料流 I/O
_cscanf, _cscanf_l, _cwscanf, _cwscanf_l
fprintf, _fprintf_l, fwprintf, _fwprintf_l
scanf, _scanf_l, wscanf, _wscanf_l
sscanf, _sscanf_l, swscanf, _swscanf_l
fscanf_s, _fscanf_s_l, fwscanf_s, _fwscanf_s_l