0

関数を使用fgets()して、固定サイズの構造体に文字列を格納しています。

if(fgets(auth_data->user_id, USR_SIZE, stdin) == NULL)
    EXIT_ON_ERROR_("Error on fgets function\n");
fflush(stdin);

USR_SIZE -1以上のサイズの受信文字列はすべてカットされていることがわかります。入力文字列が正確にそのサイズ(USR_SIZE -1プラス'\0'文字)であることを知る必要があります。

strlenこの目的のために、文字列に長さがあるかどうかを確認するためにそれらを呼び出すことができます< USR_SIZE -1。しかし、元の文字列が によって切断されたかどうかを確認するにはどうすればよいですかfgets。どちらの場合も、文字列が正しい形式ではないことが最初にわかります。

さらにfflush(stdin)、入力ストリームをクリアするために本当に必要ですか?

4

2 に答える 2

0

fgets は、改行を最後の文字としてバッファーに格納します。バッファーに改行がないということは、EOF (feof で確認) または文字列が切断されたことを意味します。

または、事前設定されたバイト数を読み取る fread() ループですべての検証コードを置き換えることができます。

入力ストリームで fflush を呼び出すのは正しくありません。GNU libc マニュアルから:

C89、C99、POSIX.1-2001、POSIX.1-2008 に準拠。

  The  standards  do  not  specify the behavior for input streams.  Most
  other implementations behave the same as Linux.

代わりに、ストリームの最後まで読み取ります (または単に閉じます)。

于 2013-03-29T18:14:21.980 に答える
0

fgetsのmanページにはDESCRIPTIONと書かれています

 The fgets() function reads at most one less than the number of characters
 specified by size from the given stream and stores them in the string
 str.  Reading stops when a newline character is found, at end-of-file or
 error.  The newline, if any, is retained.  If any characters are read and
 there is no error, a `\0' character is appended to end the string.

戻り値

 Upon successful completion, fgets() and gets() return a pointer to the
 string.  If end-of-file occurs before any characters are read, they
 return NULL and the buffer contents remain unchanged.  If an error
 occurs, they return NULL and the buffer contents are indeterminate.  **The
 fgets() and gets() functions do not distinguish between end-of-file and
 error, and callers must use feof(3) and ferror(3) to determine which
 occurred.**

ファイルからのみ多くの文字を読み取らせているため、文字が切り捨てられているかどうかはわかりません

于 2013-03-29T19:11:42.930 に答える