测试代码如下
#include "../tcpiplib.h" int main(int argc, char **argv) { ssize_t n; size_t len; char buf[10]; //memset(buf, 0, sizeof(buf)); n = 8; len = read(fileno(stdin), buf, n); write(fileno(stdout), buf, len); printf("%d strlen = %d\n",len, strlen(buf)); fgets(buf, n, stdin); len = fputs(buf, stdout); printf("%d strlen = %d\n", len, strlen(buf)); exit(0); }
输出如下
abc abc 4 strlen = 10 efg efg 1 strlen = 4
查看内存时,发现read会在按下回车后返回,并在字符串abc后加上换行符\n,但是不会再加上'\0',所以strlen有可能为10
但是fgets会在末尾加上\n\0保证正确结尾
补充:
使用scanf,输入字符串只会自动在后面补'\0',而没有换行符'\n'
初始化时
(gdb) p buf $1 = "*\000U<\026\000\371\210\004\b"
read后
(gdb) p buf $2 = "abc\n\026\000\371\210\004\b"fgets后
(gdb) p buf $3 = "12\n\000\026\000\371\210\004\b"