What will be the output of the following code? #include <stdio.h> int main() { FILE *file = fopen("test.txt", "w"); fputs("Line 1\nLine 2", file); fclose(file); file = fopen("test.txt", "r"); char buffer[50]; while (fgets(buffer, sizeof(buffer), file)) { printf("%s", buffer); } fclose(file); return 0; }Question 4AnswerA.Line 1 Line 2B.Line 1Line 2C.Compilation errorD.Runtime error
Question
What will be the output of the following code? #include <stdio.h> int main() { FILE *file = fopen("test.txt", "w"); fputs("Line 1\nLine 2", file); fclose(file); file = fopen("test.txt", "r"); char buffer[50]; while (fgets(buffer, sizeof(buffer), file)) { printf("%s", buffer); } fclose(file); return 0; }Question 4AnswerA.Line 1 Line 2B.Line 1Line 2C.Compilation errorD.Runtime error
Solution
The output of the code will be:
Line 1 Line 2
So, the correct answer is B. Line 1 Line 2.
Here's the step by step explanation:
-
The code first opens a file named "test.txt" in write mode. If the file does not exist, it will be created.
-
It then writes "Line 1\nLine 2" to the file. The "\n" is a newline character, which means it will start a new line after "Line 1".
-
The file is then closed and reopened in read mode.
-
A buffer of size 50 is created to store the lines read from the file.
-
The while loop reads the file line by line using fgets() and stores each line in the buffer. It then prints the contents of the buffer. This will print "Line 1" and "Line 2" on separate lines.
-
Finally, the file is closed and the program returns 0, indicating successful execution.
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.