- 论坛徽章:
- 0
|
today i am coding a somall program. fgets will be used in it. But i do not know this function very well, so i man it and write some test code .
char *fgets(char *s, int size, FILE *stream);
I view the function fgets in the manual. In the manual it is said like this:
fgets() reads in at most one less than size characters from stream and stores then into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A '\0' is stored after the last character in the buffer.
there are some occasions need to think about.
1. What happened if the buffer is not enough the store a line .
line:123456789/n
mem[5]:\000\000\000\000\000
if we use the mem to store the line , the result is
mem[5]:1234\0
understand ? note the last space is always '\0'.
2.what happened if the buffer is just the size of the line.
line:123456789\n
mem[10]:
the the result is :
mem[10]:123456789\0
note the last bytes stores '\0', not '\n'.
3. What happened if the buffer is larger than the size of the line
line: 123456789\n
mem[15]={0}
the result is :
mem[15]:123456789\n\000...\000
understand ?
so, this is the fgets .
when you use it next time, i think you will do well with it.
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/50866/showart_1999759.html |
|