fgets和read区别
Posted ^_^|
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了fgets和read区别相关的知识,希望对你有一定的参考价值。
char string[20];
int main()
{
write(1, ">", 1);
// read(0, string, sizeof string);
fgets(string, sizeof string, stdin);
printf("%s\\n", string);
printf("sizeof: %ld \\n", sizeof string);
for (int i = 0; i < sizeof string; i ++)
printf("%d ", string[i]);
printf("\\nstrlen: %ld \\n", strlen(string));
for (int i = 0; i < strlen(string); i++)
printf("%d ", string[i]);
printf("\\n-------------------\\n");
write(1, ">", 1);
// read(0, string, sizeof string);
fgets(string, sizeof string, stdin);
printf("%s\\n", string);
printf("sizeof: %ld \\n", sizeof string);
for (int i = 0; i < sizeof string; i ++)
printf("%d ", string[i]);
printf("\\nstrlen: %ld \\n", strlen(string));
for (int i = 0; i < strlen(string); i ++)
printf("%d ", string[i]);
puts("");
return 0;
}
--------------------结果-----------------------------
>echo a b c
echo a b c
sizeof: 20
101 99 104 111 32 97 32 98 32 99 10 0 0 0 0 0 0 0 0 0
strlen: 11
101 99 104 111 32 97 32 98 32 99 10
-------------------
>exit
exit
sizeof: 20
101 120 105 116 10 0 32 98 32 99 10 0 0 0 0 0 0 0 0 0
strlen: 5
101 120 105 116 10
char string[20];
int main()
{
write(1, ">", 1);
read(0, string, sizeof string);
// fgets(string, sizeof string, stdin);
printf("%s\\n", string);
printf("sizeof: %ld \\n", sizeof string);
for (int i = 0; i < sizeof string; i ++)
printf("%d ", string[i]);
printf("\\nstrlen: %ld \\n", strlen(string));
for (int i = 0; i < strlen(string); i++)
printf("%d ", string[i]);
printf("\\n-------------------\\n");
write(1, ">", 1);
read(0, string, sizeof string);
// fgets(string, sizeof string, stdin);
printf("%s\\n", string);
printf("sizeof: %ld \\n", sizeof string);
for (int i = 0; i < sizeof string; i ++)
printf("%d ", string[i]);
printf("\\nstrlen: %ld \\n", strlen(string));
for (int i = 0; i < strlen(string); i ++)
printf("%d ", string[i]);
puts("");
return 0;
}
----------------------------结果------------------------------------------
>echo a b c
echo a b c
sizeof: 20
101 99 104 111 32 97 32 98 32 99 10 0 0 0 0 0 0 0 0 0
strlen: 11
101 99 104 111 32 97 32 98 32 99 10
-------------------
>exit
exit
a b c
sizeof: 20
101 120 105 116 10 97 32 98 32 99 10 0 0 0 0 0 0 0 0 0
strlen: 11
101 120 105 116 10 97 32 98 32 99 10
根据上面实验可知,fgets()会自动加’\\0’,而read不会
以上是关于fgets和read区别的主要内容,如果未能解决你的问题,请参考以下文章