C File Handling - Tricky MCQ

Previous C File Handling Next

Tricky Questions on File Handling

Basic Level (15 Questions)

1

What is the difference between text mode and binary mode file opening?

Correct Answer: D) All of the above

Text mode performs newline translation: on Windows, "\n" becomes "\r\n" when writing and "\r\n" becomes "\n" when reading. Binary mode reads/writes raw bytes without translation. Text mode is platform-dependent (different behavior across OS), binary is consistent. Use text mode for human-readable files (txt, csv), binary for images, executables, or when exact byte representation matters.

2

What does fopen() return on failure?

Correct Answer: A) NULL pointer

fopen() returns a FILE* pointer on success and NULL on failure. Common failure reasons: file doesn't exist (for reading), permission denied, disk full, invalid path. Always check if fopen() returned NULL before using the file pointer to avoid segmentation faults. Use perror() or strerror(errno) to get error details after fopen() failure.

3

What is the difference between fgetc(), getc(), and getchar()?

Correct Answer: D) All of the above

fgetc() is a function, getc() is a macro (may evaluate argument multiple times), getchar() is equivalent to getc(stdin). All return int (not char) to accommodate EOF (-1) and all char values (0-255). Since getc() is a macro, avoid expressions with side effects as arguments. fgetc() is safer when stream argument has side effects. They all return EOF on end-of-file or error.

4

What is file position indicator and how is it manipulated?

Correct Answer: D) All of the above

The file position indicator tracks the current read/write location. fseek() moves it, ftell() returns current position, rewind() sets to beginning. For binary files, seeking is precise (byte offsets). For text files, only seeking to position 0 (beginning) or position from ftell() is reliable due to newline translation differences. fseek() with SEEK_END is not portable for text files.

5

What is the difference between fread()/fwrite() and fprintf()/fscanf()?

Correct Answer: D) All of the above

fread() and fwrite() perform binary I/O - they read/write raw bytes without interpretation. fprintf() and fscanf() perform formatted I/O - they convert between binary and text representations. Binary I/O is faster, preserves exact values (important for floats), and produces smaller files. Formatted I/O creates human-readable files but is slower and may lose precision. Use binary for data structures, formatted for config files.

6

What happens if you don't close a file with fclose()?

Correct Answer: D) All of the above

Not closing files causes multiple problems: 1) Memory leak - FILE structure allocated by fopen() not freed, 2) Data loss - buffered data not flushed to disk (fflush() helps but doesn't release resources), 3) Resource leak - OS file descriptors/handles are limited, 4) File locking issues on some systems. Files are automatically closed on program exit, but explicit fclose() is good practice for long-running programs.

7

What is the difference between stdin, stdout, and stderr?

Correct Answer: D) All of the above

stdin, stdout, and stderr are pre-opened FILE* streams automatically available to programs. stdin: standard input (keyboard), stdout: standard output (screen), stderr: standard error (screen). stdout is typically line-buffered when connected to terminal, stderr is unbuffered for immediate error reporting. They can be redirected: "program > file" redirects stdout, "2> file" redirects stderr. Use stderr for error messages to separate from normal output.

8

What is file buffering and how does it affect performance?

Correct Answer: D) All of the above

File buffering stores data in memory buffers before writing to disk or after reading from disk. This reduces expensive system calls (read()/write()) by batching operations. Default buffering: fully buffered for files, line-buffered for stdout to terminal, unbuffered for stderr. setbuf() and setvbuf() control buffering mode (full, line, none) and buffer size. fflush() forces buffer write. Buffering improves performance but can cause data loss on crash if not flushed.

9

What is the difference between feof() and checking return value of read functions?

Correct Answer: D) All of the above

feof() returns non-zero only after a read attempt has reached end-of-file. It doesn't predict the future. Read functions (fgetc(), fread(), etc.) return special values (EOF, 0, etc.) when they fail. The correct pattern: attempt to read, check if read succeeded, if failed, use feof() to distinguish between end-of-file and error, or ferror() for error details. Never use feof() as loop condition - it leads to off-by-one errors.

10

Can you open the same file multiple times with different modes?

Correct Answer: D) All of the above

You can open the same file multiple times with fopen(), creating independent FILE* streams. However, this leads to problems: 1) Buffering causes data written through one stream to not be visible to another until flushed, 2) Overlapping reads/writes cause undefined behavior, 3) File position indicators are independent, causing confusion. The C standard says behavior is undefined for most operations on the same file through different streams. Use a single stream or proper file locking.

11

What is the difference between remove() and unlink() for deleting files?

Correct Answer: D) All of the above

remove() is standard C library function, unlink() is POSIX system call. remove() can delete both files and empty directories (like rmdir()), unlink() only deletes files. Both immediately remove directory entry; actual disk space freed when no processes have file open (reference count zero). On Windows, remove() may fail if file is open; on Unix, unlink() succeeds even if file is open (space freed when last handle closed).

12

What is temporary file creation and why use it?

Correct Answer: D) All of the above

Temporary files store intermediate data. tmpfile() creates unnamed temporary file in binary update mode (w+b), automatically deleted when closed or program exits. tmpnam() generates unique filename but has race condition (another process could create file with same name before you do). mkstemp() (POSIX) creates file with unique name atomically, returns file descriptor. Always use tmpfile() or mkstemp() for security; avoid tmpnam().

13

What is the difference between ferror() and errno for file error detection?

Correct Answer: D) All of the above

ferror() tests the error indicator for a specific FILE* stream, returning non-zero if error occurred on that stream. errno is a global integer variable set by failed system/library calls to indicate error type. Use ferror() after failed stream operation to check if it was an error (vs EOF). Use perror() or strerror(errno) to get human-readable error message. Clear errors with clearerr() to reuse stream after error.

14

What is random access vs sequential access in files?

Correct Answer: D) All of the above

Sequential access reads/writes data in order from start to end. Random access (direct access) allows jumping to any position using file position indicator. fseek() moves to specific position, ftell() returns current position, rewind() goes to beginning. Binary files support precise random access with byte offsets. Text files have limited random access due to newline translation; only seeking to positions obtained from ftell() or to beginning is reliable.

15

What is file descriptor vs FILE pointer?

Correct Answer: D) All of the above

File descriptor (int, like 0,1,2 for stdin,stdout,stderr) is low-level OS handle returned by open(). FILE* is high-level stream structure from stdio.h with buffering, error handling, formatted I/O. Standard library uses descriptors internally but adds features. fileno() gets descriptor from FILE*; fdopen() creates FILE* from descriptor. Use descriptors for low-level control (non-blocking I/O, file locking), FILE* for buffered/formatted I/O. Always close both consistently.

Hard Level (15 Questions)

16

`fopen("f.txt", "r+")` allows:

Correct Answer: A) Read and write; file must exist

r+ opens for update reading and writing; fails if file does not exist.

17

`fread(buf, 1, 100, fp)` returns:

Correct Answer: A) Number of elements (size 1) read, may be <100

Return is complete elements read; short return on error/EOF.

18

Text mode `fprintf` with '\n' on Windows may:

Correct Answer: A) Write \r\n

Text mode may translate newline on some systems.

19

`ftell` after binary read on text stream:

Correct Answer: A) May not reflect byte offset portably

Text streams can have encoding transformations; ftell on text may be misleading.

20

`remove("a.txt")` on open file:

Correct Answer: A) Implementation-defined whether removal succeeds

Removing open file behavior varies by OS.

21

`rename` atomicity:

Correct Answer: A) Not required by C standard

rename behavior including replace is implementation-defined.

22

`fseek(fp, 0, SEEK_END); ftell(fp);` returns:

Correct Answer: A) File size in bytes for binary stream typically

Seeking end then ftell commonly yields size for binary files.

23

`feof(fp)` returns true:

Correct Answer: A) After read attempt past last data

feof is set after failed read due to EOF; not predictive before read.

24

`tmpfile()` creates:

Correct Answer: A) Temporary file automatically removed on close

tmpfile opens a temporary binary file removed on fclose or exit.

25

`fgetc` returns unsigned char cast to int or EOF:

Correct Answer: A) int value 0-255 or EOF negative

fgetc returns unsigned char converted to int or EOF macro.

26

Opening with "wb" on POSIX:

Correct Answer: A) Binary mode no translation

b suffix disables text translation where applicable.

27

`setbuf(fp, NULL)`

Correct Answer: A) Disables buffering if possible

NULL buffer with setbuf makes stream unbuffered when supported.

28

`fwrite` return value less than requested indicates:

Correct Answer: A) Error or partial write

Short fwrite indicates error or incomplete write.

29

`perror("msg")` prints:

Correct Answer: A) msg plus system error string for errno

perror outputs user message and strerror(errno) to stderr.

30

fflush before fclose on output stream:

Correct Answer: A) Good practice; fclose flushes anyway

fclose flushes unwritten data; explicit fflush can surface errors earlier.

Previous C File Handling Next