fgetsfgetws

从流获取字符串。

语法

char *fgets(
   char *str,
   int numChars,
   FILE *stream
);
wchar_t *fgetws(
   wchar_t *str,
   int numChars,
   FILE *stream
);

参数

str
数据的存储位置。

numChars
要读取的最大字符数。

stream
指向 FILE 结构的指针。

返回值

其中每个函数都会返回 str。 将返回 NULL 指示错误或文件尾条件。 使用 feofferror 确定是否出错。 如果 strstream 是空指针,或者 numChars 小于或等于零,此函数会调用无效的参数处理程序,如参数验证中所述。 如果允许继续执行,则将 errno 设置为 EINVAL 并且该函数返回 NULL中所述。

有关返回代码的详细信息,请参阅 errno_doserrno_sys_errlist_sys_nerr

备注

fgets 函数将读取输入 stream 参数中的一个字符串,并将其存储到 str 中。 fgets 会将字符从当前流位置读取到流的结尾(包含第一个换行符),或直到读取的字符数量等于 numChars - 1,以先到者为准。 将向存储在 str 中的结果追加一个 null 字符。 换行符(如果读取)将包括在字符串中。

fgetwsfgets 的宽字符版本。

stream 分别以文本模式或二进制模式打开时,fgetws 会将宽字符自变量 str 作为多字节字符串或宽字符串读取。 若要详细了解如何在 Unicode 和多字节流 I/O 中使用文本和二进制模式,请参阅文本和二进制模式文件 I/O文本和二进制模式下的 Unicode 流 I/O

默认情况下,此函数的全局状态范围限定为应用程序。 若要更改此行为,请参阅 CRT 中的全局状态

一般文本例程映射

TCHAR.H 例程 _UNICODE_MBCS 未定义 _MBCS 已定义 _UNICODE 已定义
_fgetts fgets fgets fgetws

要求

函数 必需的标头
fgets <stdio.h>
fgetws <stdio.h><wchar.h>

有关兼容性的详细信息,请参阅 兼容性

示例

// crt_fgets.c
// This program uses fgets to display
// the first line from a file.

#include <stdio.h>

int main( void )
{
   FILE *stream;
   char line[100];

   if( fopen_s( &stream, "crt_fgets.txt", "r" ) == 0 )
   {
      if( fgets( line, 100, stream ) == NULL)
         printf( "fgets error\numChars" );
      else
         printf( "%s", line);
      fclose( stream );
   }
}

输入:crt_fgets.txt

Line one.
Line two.

输出

Line one.

另请参阅

流 I/O
fputsfputws
gets_getws
puts_putws