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 5 of 6.

Nutan said:   1 decade ago
@kamal dua

Thanks for explain it.....

Vivek said:   1 decade ago
Please any one clear exlpain.

I don't understand.
(1)

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!

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

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

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.

Nisha said:   1 decade ago
Everyone wrote whatever is already known, but the question is still unanswered. Why the hell \r didn't get stored while \n does!

Anyone. Give the to 'to the point answer' plz!

Varsha said:   1 decade ago
@Sundar

Thank you.

Sushil said:   1 decade ago
Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or a the End-of-File is reached, whichever comes first.

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

A null character is automatically appended in str after the characters read to signal the end of the C string.

Riya said:   1 decade ago
@Sundar : Thanks for the perfect explanation.


Post your comments here:

Your comments will be displayed after verification.