Complete the code to open a file named "data.txt" 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. If the file does not exist, fopen returns NULL.
Complete the code to close the opened file pointer named "fp".
#include <stdio.h> int main() { FILE *fp = fopen("log.txt", "w"); if (fp == NULL) { return 1; } // Write something to the file fprintf(fp, "Hello, file!\n"); [1](fp); return 0; }
The function fclose(fp) closes the file associated with the file pointer fp.
Fix the error in the code to open a file for appending text.
#include <stdio.h> int main() { FILE *file = fopen("output.txt", "[1]"); if (file == NULL) { perror("Failed to open file"); return 1; } fprintf(file, "Appending this line.\n"); fclose(file); return 0; }
The mode "a" opens the file for appending. It writes data at the end of the file without truncating it.
Fill both blanks to open a file for writing and check if it opened successfully.
#include <stdio.h> int main() { FILE *fp = fopen("test.txt", "[1]"); if (fp == [2]) { perror("Cannot open file"); return 1; } fclose(fp); return 0; }
Use "w" to open the file for writing. fopen returns NULL if it fails to open the file.
Fill all three blanks to open a file for reading, check for errors, and close it.
#include <stdio.h> int main() { FILE *file = fopen("input.txt", "[1]"); if (file == [2]) { perror("Error opening file"); return 1; } // File operations here [3](file); return 0; }
Open the file with mode "r" for reading. Check if the file pointer is NULL to detect errors. Use fclose to close the file.