Which function is commonly used to read formatted input from a file in C?
A
printf() B
fgets() C
fscanf() D
readfile()
Analysis & Theory
`fscanf()` is used to read formatted input from a file.
What mode should you use with `fopen()` to read an existing file?
A
"r" B
"w" C
"rw" D
"a"
Analysis & Theory
`"r"` opens a file for reading. The file must already exist.
Which of these functions reads a line (string) from a file?
A
fputs() B
fscanf() C
fgets() D
fwrite()
Analysis & Theory
`fgets()` reads a line (up to newline or buffer size) from a file.
What does `fopen("data.txt", "r")` do if the file doesn’t exist?
A
Creates a new file B
Returns NULL C
Writes to the file D
Appends data
Analysis & Theory
If the file doesn’t exist, opening in `"r"` mode returns `NULL`.
Which function checks for the end of a file in C?
A
feof() B
fend() C
file_end() D
eof()
Analysis & Theory
`feof(FILE*)` returns true when the end of file is reached.
What is the output of this code if `file.txt` contains `Hello`?
```c
char str[10];
FILE *fp = fopen("file.txt", "r");
fgets(str, 10, fp);
printf("%s", str);
```
A
Nothing B
Hello C
Error D
str
Analysis & Theory
`fgets()` reads up to 9 characters and a null terminator, printing `Hello`.
What should you do after you finish reading from a file?
A
Flush it B
Rewind it C
Reset it D
Close it using fclose()
Analysis & Theory
`fclose()` should be called to properly close the file.
Which function can be used to read binary data from a file?
A
fscanf() B
fgets() C
fread() D
fputs()
Analysis & Theory
`fread()` is used for reading binary data from a file.
How can you check if a file was successfully opened?
A
Check if the file size is > 0 B
Check if the file name is valid C
Check if `fopen()` returns NULL D
Use `filecheck()`
Analysis & Theory
Always verify the file pointer: `if (fp == NULL)`.
What will happen if you use `fscanf()` to read from a closed file?
A
It will open the file automatically B
It will create a new file C
It will result in undefined behavior D
It will reset the file
Analysis & Theory
Using file functions on a closed or NULL pointer causes undefined behavior.