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

Amaresh said:   1 decade ago
Explain in details the answer.

Rahul said:   1 decade ago
What about \r ? Why it is not reading? Can any one explain this please?
(1)

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

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

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.

Sundar said:   1 decade ago
@Nayna

Let us know the difference between the \r and \n.

\r - is moves the cursor to the left-most position of the CURRENT line.

\n - is moves the cursor to the left-most position of the NEXT line.

Example:

1. printf("India\rBIX");

Output: BIXia

2. printf("India\nBIX");

Output:

India
BIX

Note: It may not work as I said in 32-bit platform. But works fine in Turbo C (under DOS 16-bit platform).

Hope the understand the difference. Have a nice day!

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

and plz give me explanation that why \n is printed???????

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

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.

Varsha said:   1 decade ago
@Sundar

Thank you.


Post your comments here:

Your comments will be displayed after verification.