Complete the code to open a file for reading.
#include <stdio.h> int main() { FILE *file = fopen("data.txt", "[1]"); if (file == NULL) { perror("Error opening file"); return 1; } fclose(file); return 0; }
The mode "r" opens the file for reading only.
Complete the code to open a file for writing, creating it if it doesn't exist.
#include <stdio.h> int main() { FILE *file = fopen("output.txt", "[1]"); if (file == NULL) { perror("Error opening file"); return 1; } fprintf(file, "Hello, World!\n"); fclose(file); return 0; }
The mode "w" opens the file for writing and creates it if it doesn't exist.
Fix the error in the code to open a file for appending text.
#include <stdio.h> int main() { FILE *file = fopen("log.txt", "[1]"); if (file == NULL) { perror("Error opening file"); return 1; } fprintf(file, "New log entry\n"); fclose(file); return 0; }
The mode "a" opens the file for appending, writing data at the end.
Fill both blanks to open a file for reading and writing without truncating it.
#include <stdio.h> int main() { FILE *file = fopen("data.txt", "[1][2]"); if (file == NULL) { perror("Error opening file"); return 1; } // Read and write operations fclose(file); return 0; }
The mode "r+" opens the file for both reading and writing without truncating it.
Fill both blanks to open a file for writing and reading, truncating it if it exists.
#include <stdio.h> int main() { FILE *file = fopen("report.txt", "[1][2]"); if (file == NULL) { perror("Error opening file"); return 1; } // Write and read operations fclose(file); return 0; }
The mode "w+" opens the file for both writing (truncating if it exists) and reading.
