Knowee
Questions
Features
Study Tools

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

...expand
🧐 Not the exact question you are looking for?Go ask a question

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:

  1. The code first opens a file named "test.txt" in write mode. If the file does not exist, it will be created.

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

  3. The file is then closed and reopened in read mode.

  4. A buffer of size 50 is created to store the lines read from the file.

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

  6. Finally, the file is closed and the program returns 0, indicating successful execution.

This problem has been solved

Similar Questions

What will be the output of the following program?

What will be the output of the following C code?

What will be the output of the following C++ code?

What is the output of the following code in Python?

What will print out when the following code runs?

1/4

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.