C Programming - Input / Output - Discussion

Discussion Forum : Input / Output - General Questions (Q.No. 1)
1.
In a file contains the line "I am a boy\r\n" then on reading this line into the array str using fgets(). What will str contain?
"I am a boy\r\n\0"
"I am a boy\r\0"
"I am a boy\n\0"
"I am a boy"
Answer: Option
Explanation:

Declaration: char *fgets(char *s, int n, FILE *stream);

fgets reads characters from stream into the string s. It stops when it reads either n - 1 characters or a newline character, whichever comes first.

Therefore, the string str contain "I am a boy\n\0"

Discussion:
57 comments Page 4 of 6.

Nayna said:   1 decade ago
Can anyone explain me...
Why \r doesn't get read..
and if your ans is that because it is a carraige return.
then why \n gets read..it is also a new line type.

Sairamteja said:   1 decade ago
The question is good and \r is a carriage return.

NISHANTH SHETTY K said:   1 decade ago
Because it is a carraige return. It does not store in str.

Amaresh said:   2 decades ago
Explain in details the answer.

Sharmi said:   1 decade ago
Thanks sundar. Nice explanation.

Nischal said:   1 decade ago
@Sundar

I didn't get your example.

\r is to move cursor to left most position in the current line

printf("india\rbix");

Here output must be, first it prints india then \r so again cursor is moved to left most position right?

Please help me this doubt.

Nikita said:   1 decade ago
Why in ans there is '\0'.

Jyoti said:   1 decade ago
Nikita, because In C string always ended with null (\0) character.

Kamal dua said:   1 decade ago
This question is on I/O.
In C when we attempt to write a string(which is done using function fputs()).

It converts "\n" into "\r\n".

But while reading using function(which is done using function fgets()). "\r\n" is converted to "\n".

Actually this is a feature of standard library functions.

Hope you guys understand. Have a nice day!

Varsha said:   1 decade ago
@Sundar

Thank you.


Post your comments here:

Your comments will be displayed after verification.