共用方式為


fscanf、_fscanf_l、fwscanf、_fwscanf_l

從資料流讀取格式化的資料。 這些函式已有更安全的版本可用,請參閱 fscanf_s、_fscanf_s_l、fwscanf_s、_fwscanf_s_l

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 表示未指定欄位。 如果發生錯誤,或者在第一個轉換前就已經到達檔案檔案資料流結尾,則傳回值會是 fscanf 和 fwscanf 的 EOF。

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

備註

fscanf 函式會將 stream 目前位置的資料讀取到 argument 引數清單 (如果有) 所指定的位置。 清單中的所有 argument 都必須是變數的指標,這些變數的類型對應至 format 的類型規範。 format 控制輸入欄位的解譯,其與 scanf 的 format 引數有相同的形式和運作方式。如需 format*.* 的描述,請參閱 scanf

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

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

一般文字常式對應

TCHAR.H 常式

_UNICODE & _MBCS 未定義

_MBCS 已定義

_UNICODE 已定義

_ftscanf

fscanf

fscanf

fwscanf

_ftscanf_l

_fscanf_l

_fscanf_l

_fwscanf_l

如需詳細資訊,請參閱 格式規格欄位— scanf 函式和 wscanf 函式

需求

功能

必要的標頭

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

.NET Framework 對等用法

System::IO::StreamReader::ReadLine.請參閱 Parse 方法,例如 System::Double::Parse

請參閱

參考

資料流 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