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.....

Surendra said:   1 decade ago
@kamal Dua
You are right dude.... That's why it printed \n instead of "\r\n".
Thnx.........

Yami said:   1 decade ago
Sundar : Thanks for the nice explanation.

Avinash said:   1 decade ago
Considering all your explanations about \r.
What will str contain if file contains: "india\rbix"?

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.

Viswanath said:   1 decade ago
Depends on the OS guys. In windows, the line break is \r\n but in linux the line break is \n. So when it reads \r, it automatically understands that it has reached end of line and hence stops further input. GCC must have done the same to allow consistency between various OSes. Not sure though.

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!

Isvariyaa said:   1 decade ago
Also gets printed in Turbo C compiler.

Gyani said:   1 decade ago
And the question still remains the same. Why not ?

"\r\r\n" is stored and why not?

"\r\n" is returned?

Sakshi said:   1 decade ago
Explain this again please.

1. printf("India\rBIX");

Output: BIXia.


Post your comments here:

Your comments will be displayed after verification.