fgets, fgetws

從資料流取得字串。

語法

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 是 Null 指標,或 numChars 小於或等於零,則此函式會叫用不正確參數處理常式,如參數驗證 中所述 。 若允許繼續執行, errno 會設為 EINVAL ,且函式會傳回 NULL中所述。

如需傳回碼的詳細資訊,請參閱 errno_doserrno_sys_errlist_sys_nerr

備註

fgets 函式會從輸入 stream 引數讀取字串,並將其儲存在 strfgets 將目前資料流程位置中的字元讀入 ,並包括第一個新行字元、資料流程結尾,或直到讀取的字元數等於 numChars - 1,以第一個字元為准。 str 中所儲存的結果會附加 Null 字元。 讀取的新行字元包含在字串中。

fgetwsfgets 的寬字元版本。

fgetws當以文字模式或二進位模式開啟時 stream ,將寬字元引數 str 讀取為多位元組字元字串或寬字元字串。 如需在 Unicode 和多位元組 stream-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
fputs, fputws
gets, _getws
puts, _putws