2013-03-29 53 views
0

我使用fgets()函数将字符串存储在具有固定大小的结构中。stdin检索时的输入行大小

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)吗?

回答

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. 

相反,一直读到流的末尾(或直接关闭它)。与fgets的

+0

一个'read'调用将永远不会到达'EOF'而不用CTRL D强制它。我得到的是第主要过程在等待。还有另一种方式? –

0

手册页说 说明

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.** 

它永远不会知道,如果你正在使读取任何字符将被截断,只有从众多人物文件