C Programming Tricky Questions

Tricky Questions on File Handling

What is the difference between text files and binary files in C?
Text files store data as human-readable characters with newline conversions. Binary files store raw bytes without conversions. Text mode performs newline translation (\\n to \\r\\n on Windows), binary mode does not.
What are the different file opening modes in C?
Common modes: "r" (read), "w" (write, truncate/create), "a" (append), "r+" (read/write), "w+" (read/write, truncate/create), "a+" (read/append). Adding "b" makes it binary mode ("rb", "wb", etc.).
Tricky Point: "w" and "w+" truncate files to zero length if they exist. Use "a" or "a+" to preserve existing content.
What is FILE pointer and why is it used?
FILE is a structure defined in stdio.h that contains file information. FILE* is a pointer to this structure, used by all file functions to track file position, buffering, and status.
What is file buffering and why is it used?
Buffering stores data in memory before writing to disk (or reading from disk). Improves performance by reducing disk I/O operations. Three types: fully buffered, line buffered, unbuffered.
What happens if you don't close a file after using it?
Memory leak (FILE structure not freed), data loss (buffered data not flushed), file descriptor/handle leak (OS resource), and potential file corruption. Always close files with fclose().
What is the difference between fgets() and gets()?
fgets() reads specified number of characters, includes newline, and is safe. gets() reads until newline, doesn't include newline, and is dangerous (buffer overflow). gets() is removed from C11.
What is file positioning and which functions control it?
File positioning tracks read/write location. Functions: ftell() gets current position, fseek() sets position, rewind() sets to beginning. Important for random access files.
What is the difference between fprintf() and fwrite()?
fprintf() writes formatted text (like printf() to file). fwrite() writes raw binary data. fprintf() is for text files, fwrite() for binary files or structured data.
What is end-of-file (EOF) and how is it detected?
EOF indicates end of file. feof() checks EOF flag, but reading functions (fgetc(), fscanf(), etc.) return special value (usually -1 for fgetc()). feof() only returns true AFTER failed read.
What is the difference between fflush() and fsync()?
fflush() writes buffered data to OS buffer. fsync() (POSIX) ensures data is physically written to disk. fflush() doesn't guarantee disk write, just clears program buffer.
What are file descriptors vs FILE pointers?
File descriptors (int) are low-level POSIX handles. FILE pointers are high-level C library wrappers. fopen() returns FILE*, open() returns file descriptor. C functions use FILE*, system calls use descriptors.
What is the difference between text mode and binary mode on different platforms?
On Unix/Linux: no difference (\\n is newline). On Windows: text mode converts \\n to \\r\\n when writing and \\r\\n to \\n when reading. On Mac (old): text mode uses \\r as newline.
What happens when you open a non-existent file in read mode?
fopen() returns NULL. Always check return value of fopen(). Never assume file opening succeeded. Common error: not checking NULL and then using invalid FILE pointer.
Warning: Using NULL FILE pointer causes segmentation fault or undefined behavior.
What is the difference between fread()/fwrite() and read()/write()?
fread()/fwrite() are buffered C library functions. read()/write() are unbuffered POSIX system calls. C functions are portable, system calls are OS-specific but more control.
What is file locking and why is it important?
File locking prevents multiple processes from accessing file simultaneously. Important for data consistency. Types: advisory (cooperative) vs mandatory (enforced), shared (read) vs exclusive (write).
What is the difference between rename() and moving files?
rename() changes file name/path within same filesystem. Moving files across devices requires copy+delete. rename() fails if target exists (on most systems) or across filesystems.
What is temporary file and how to create it safely?
Temporary file exists only during program execution. Use tmpfile() (C library) or mkstemp() (POSIX). tmpnam() is unsafe (race condition). Always create with unique names to avoid conflicts.
What is the difference between ferror() and feof()?
ferror() checks error flag (I/O error occurred). feof() checks EOF flag (end of file reached). Both clear flags after calling clearerr(). Check ferror() after I/O operations fail.
What is file truncation and how is it done?
Truncation reduces file size. Methods: open with "w" mode (truncates to zero), freopen() with "w", ftruncate() (POSIX), or seek+write. Opening existing file with "w" destroys content.
What is the difference between standard streams and regular files?
Standard streams: stdin, stdout, stderr (pre-opened). Regular files: opened with fopen(). Standard streams may be buffered differently (stdout line-buffered if terminal).
What is file permissions and how are they set in C?
File permissions control read/write/execute access. Set using chmod() (POSIX) or umask() for new files. fopen() uses default permissions (0666 modified by umask).
What is the difference between sequential and random access files?
Sequential: read/write in order (faster for streaming). Random: access any position directly (fseek()/ftell()). All files support both, but performance differs based on access pattern.
What is file existence check and why is TOCTOU a problem?
Check with access() or stat(). TOCTOU (Time of Check, Time of Use) race condition: file changes between check and use. Solution: attempt operation and handle errors instead of checking first.
What is file descriptor limit and how to handle it?
OS limits open files per process. Check with getrlimit(). Handle by: closing unused files, using select/poll for many files, increasing limit with setrlimit(), or using file descriptor pooling.
What is the difference between C file I/O and C++ file streams?
C uses FILE* and functions (fopen, fprintf, fscanf). C++ uses objects (fstream, ifstream, ofstream) and operators (<<, >>). C is lower-level, C++ provides type safety and RAII.
Tricky Point: Mixing C and C++ I/O on same file can cause buffering issues and undefined behavior due to different buffering strategies.
Note: These tricky questions cover important concepts about file handling in C, including file modes, buffering, error handling, platform differences, and best practices. Understanding file I/O is crucial for writing robust programs that interact with the filesystem.
Previous File Handling Next