Complete the code to open a file for reading.
#include <stdio.h> int main() { FILE *file = fopen("example.txt", "[1]"); if (file == NULL) { printf("Failed to open file.\n"); return 1; } fclose(file); return 0; }
To read from a file, you must open it in read mode using "r".
Complete the code to write a string to a file.
#include <stdio.h> int main() { FILE *file = fopen("output.txt", "[1]"); if (file == NULL) { printf("Cannot open file.\n"); return 1; } fprintf(file, "Hello, file handling!\n"); fclose(file); return 0; }
To write to a file, open it in write mode using "w".
Fix the error in the code to append text to an existing file.
#include <stdio.h> int main() { FILE *file = fopen("log.txt", "[1]"); if (file == NULL) { printf("Error opening file.\n"); return 1; } fprintf(file, "New log entry\n"); fclose(file); return 0; }
To add data at the end of a file without erasing existing content, use append mode "a".
Fill both blanks to read a character from a file and check for end of file.
#include <stdio.h> int main() { FILE *file = fopen("data.txt", "r"); int ch; if (file == NULL) { printf("Cannot open file.\n"); return 1; } while ((ch = [1](file)) != [2]) { putchar(ch); } fclose(file); return 0; }
Use fgetc to read a character from the file and compare it with EOF to detect end of file.
Fill all three blanks to write and then read a string from a file.
#include <stdio.h> int main() { char str[50]; FILE *file = fopen("test.txt", "[1]"); if (file == NULL) { printf("File open error.\n"); return 1; } fprintf(file, "Hello World\n"); fclose(file); file = fopen("test.txt", "[2]"); if (file == NULL) { printf("File open error.\n"); return 1; } fgets(str, sizeof(str), file); printf("Read from file: %s", [3]); fclose(file); return 0; }
Open the file in write mode "w" to write, then in read mode "r" to read. Use the variable str to print the read string.
