Share via


fscanf_s、_fscanf_s_l、fwscanf_s、_fwscanf_s_l

从流中读取格式化数据。 fscanf、_fscanf_l、fwscanf、_fwscanf_l 的这些版本如 CRT 中的安全功能 所述,其安全得到了增强。

int fscanf_s( 
   FILE *stream,
   const char *format [,
   argument ]... 
);
int _fscanf_s_l( 
   FILE *stream,
   const char *format,
   locale_t locale [,
   argument ]... 
);
int fwscanf_s( 
   FILE *stream,
   const wchar_t *format [,
   argument ]... 
);
int _fwscanf_s_l( 
   FILE *stream,
   const wchar_t *format,
   locale_t locale [,
   argument ]... 
);

参数

  • stream
    指向 FILE 结构的指针。

  • format
    窗体控件字符串。

  • argument
    可选参数。

  • locale
    要使用的区域设置。

返回值

每个函数返回成功转换并分配的字段数量;返回值不包括已读取但未分配的字段。 返回值为 0 表示未分配字段。 如果出现错误,或者,如果在第一个转换之前到达文件流的末尾,则返回值是 fscanf_s 的 EOF 和 fwscanf_s。

这些函数验证其参数。 如果 stream 是无效的文件指针,或者 format 是 null 指针,则这些函数将调用无效参数处理程序,如 参数验证 中所述。 如果允许执行继续,则这些函数返回 EOF 并将 errno 设置为 EINVAL。

备注

fscanf_s 函数从 stream 当前位置中读取数据到由 argument 参数列表(如果有)给定的位置中。 argument 列表中的每个参数必须是指向类型变量的指针,此类型需与format中的类型说明符对应。 format 控件输入字段的说明并且具有的窗体和函数和 scanf_s的 format 参数相同;想了解 format的声明,请参见 格式规范字段:scanf 和 wscanf 函数 。fwscanf_s 是 fscanf_s的宽字符版本; fwscanf_s 的 format 参数是宽字符字符串。 如果流在 ANSI 模式中打开,这些函数具有相同的行为。 fscanf_s 当前不支持 UNICODE 流的输入。

更安全函数(具有 _s 后缀)和其他版本之间的主要差异在于更安全函数需要每个 c、C、s、S 和 [ 类型字段的字符数作为紧跟该变量的参数传递。 有关更多信息,请参见scanf_s、_scanf_s_l、wscanf_s、_wscanf_s_lscanf 宽度规范

备注

大小参数的类型为 unsigned 而非 size_t。

这些带有 _l 后缀的函数的版本相同,除了它们传递的是区域设置参数而不是当前线程区域设置。

一般文本例程映射

TCHAR.H 例程

未定义 _UNICODE & _MBCS

已定义 _MBCS

已定义 _UNICODE

_ftscanf_s

fscanf_s

fscanf_s

fwscanf_s

_ftscanf_s_l

_fscanf_s_l

_fscanf_s_l

_fwscanf_s_l

要求

功能

必需的标头

fscanf_s, _fscanf_s_l

<stdio.h>

fwscanf_s, _fwscanf_s_l

<stdio.h> 或 <wchar.h>

有关其他兼容性信息,请参见兼容性

示例

// crt_fscanf_s.c
// This program writes formatted
// data to a file. It then uses fscanf to
// read the various data back from the file.
 
#include <stdio.h>
#include <stdlib.h>

FILE *stream;

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

   errno_t err = fopen_s( &stream, "fscanf.out", "w+" );
   if( err )
      printf_s( "The file fscanf.out was not opened\n" );
   else
   {
      fprintf_s( stream, "%s %ld %f%c", "a-string", 
               65000, 3.14159, 'x' );
      // Set pointer to beginning of file:
      fseek( stream, 0L, SEEK_SET );

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

      fscanf_s( stream, "%f", &fp );
      fscanf_s( stream, "%c", &c, 1 );

      // 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_s、_cscanf_s_l、_cwscanf_s、_cwscanf_s_l

fprintf_s、_fprintf_s_l、fwprintf_s、_fwprintf_s_l

scanf_s、_scanf_s_l、wscanf_s、_wscanf_s_l

sscanf_s、_sscanf_s_l、swscanf_s、_swscanf_s_l

fscanf、_fscanf_l、fwscanf、_fwscanf_l