函数原型:char *fgets(char *restrict s, int n, FILE *restrict stream);
description: The fgets() function shall read bytes from stream into the array pointed to by s, until n-1 bytes are read, or a <newline> is read and transferred to s, or an end-of-file condition is encountered. The string is then terminated with a null byte.
在pro*c例子中看到类似这样的代码:
printf("please input your username:");
fgets(username,sizeof(username),stdin);
username[strlen(username)-1]='/0';
oracle登陆输入用户名和密码大概类似上面所写,我所奇怪的是上面所示最后一行代码,看fgets()函数描述可知该函数遇到换行符会停止输入并将换行符写入字符串中,然后补'/0',所以该行代码作用是去掉回车符并不奇怪,但是当输入字符数是(sizeof(username)-1)时会怎么样呢?应该也是停止输入,然后补'/0',这样上面的代码就会丢掉一个字符,在windows平台下测试发现确实如此,下面是一个简单的小测试程序:
#include <stdio.h>
#include <string.h>
#define LEN 5
int main(int argc, char **argv)
{
char buf[LEN];
fgets((char *)buf, sizeof(buf), stdin);
// buf[strlen((char *)buf)-1] = '/0';
printf("buf is %s, and its length is %d", buf, strlen(buf));
return 0;
}
当输入字符串长度小于sizeof(buf)-1时,输入'abc',输出为:
buf is abc
, and its length is 4; // 这样字符串含有回车符,有问题
但是输入字符串长度等于sizeof(buf)-1时, 输入'abcd', 输出为:
buf is abc, and its length is 4; // 直接在最后一个字符处补'/0', 没回车符,是想要的结果
所以利用buf[strlen((char *)buf)-1] = '/0';一句去掉回车符,当输入字符串长度等于sizeof(buf)-1时会丢失一个字符,不过这种情况可能应该可以忽略吧,不过好像也算是一个小小的问题吧。