Complete the code to open a file named "output.txt" for writing.
#include <stdio.h> int main() { FILE *file = fopen("output.txt", "[1]"); if (file == NULL) { perror("Error opening file"); return 1; } fclose(file); return 0; }
Use "w" mode to open a file for writing. It creates the file if it doesn't exist and truncates it if it does.
Complete the code to write the string "Hello, World!" to the file.
#include <stdio.h> int main() { FILE *file = fopen("output.txt", "w"); if (file == NULL) { perror("Error opening file"); return 1; } fprintf(file, "[1]\n"); fclose(file); return 0; }
The string to write is exactly "Hello, World!" including the comma and exclamation mark.
Fix the error in the code to properly close the file after writing.
#include <stdio.h> int main() { FILE *file = fopen("output.txt", "w"); if (file == NULL) { perror("Error opening file"); return 1; } fprintf(file, "Hello, World!\n"); [1](file); return 0; }
Use fclose() to close a file opened with fopen().
Fill both blanks to write an integer value 42 to the file using fprintf.
#include <stdio.h> int main() { FILE *file = fopen("output.txt", "w"); if (file == NULL) { perror("Error opening file"); return 1; } int number = 42; fprintf(file, "[1]", [2]); fclose(file); return 0; }
Use the format specifier "%d" to print an integer, and pass the variable number as argument.
Fill all three blanks to write multiple lines to a file using fprintf inside a loop.
#include <stdio.h> int main() { FILE *file = fopen("output.txt", "w"); if (file == NULL) { perror("Error opening file"); return 1; } for (int i = 1; i <= 3; i++) { fprintf(file, [1], [2], [3]); } fclose(file); return 0; }
The format string "Line %d: %s\n" prints the line number and a string. Pass i and "Hello" as arguments.