Why is file handling important in programming?
Think about what happens to data when a program closes.
File handling lets programs save data permanently on disk, so it is not lost when the program ends. This is why it is important.
What will be the output of this C code?
#include <stdio.h> int main() { FILE *fp = fopen("test.txt", "w"); if (fp == NULL) { printf("Error opening file\n"); return 1; } fprintf(fp, "Hello World\n"); fclose(fp); printf("File written successfully\n"); return 0; }
Look at what is printed to the screen, not what is written inside the file.
The program writes "Hello World" to the file but prints "File written successfully" to the screen.
What error will this C code produce when run?
#include <stdio.h> int main() { FILE *fp = fopen("nonexistent.txt", "r"); char buffer[20]; fgets(buffer, 20, fp); printf("%s", buffer); fclose(fp); return 0; }
What happens if fopen fails and returns NULL, then you use that pointer?
If fopen fails to open the file, fp is NULL. Using fgets on NULL causes a segmentation fault (runtime crash).
Why do programs use file handling when working with large amounts of data?
Think about the limits of computer memory versus disk storage.
Memory is limited and temporary. Large data is stored in files on disk to handle more data than memory can hold.
Consider this C code that counts lines in a file. What is the value of count after running?
#include <stdio.h> int main() { FILE *fp = fopen("data.txt", "r"); int count = 0; char ch; if (fp == NULL) return 1; while ((ch = fgetc(fp)) != EOF) { if (ch == '\n') count++; } fclose(fp); printf("%d\n", count); return 0; }
Look at what the code counts inside the loop.
The code counts how many newline characters '\n' appear in the file, which equals the number of lines.