简体   繁体   中英

fgets adds \0 or \n at the end of the input?

I've some doubts about fgets. From what I know, it adds "\n" at the end of the string, and not "\0". So if I write this code:

fgets(buff,2,stdin);
printf("%s",buff);

So fgets reads two characters, I give as input "y", so buff should be "y\n". I'd expect printf to print y and add a line, while it prints "y" without adding a line. Can you explain why?

char * fgets ( char * str, int num, FILE * stream );

Reads characters from input stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.

A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str.

A terminating null character ('\\0') is automatically appended after the characters copied to str.

It must terminate the string, so yes it will always add '\\0' at the end. However, fgets might not always add the newline, if it doesn't fit. I recommend this reference page for fgets .

According to man page it clearly given :

 char *fgets(char *s, int size, FILE *stream);

fgets() reads in at most one less than size characters from stream and stores them 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.

fgets() adds \0 at the end but it reads the string with \n if it exists in the file

i have such thing after reading string: "guitar\n\0\U00000004\xd5..."

my file had string with word "guitar" and \n after it so, as u see it read the word with "\n" and added "\0" to the string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM