- How to open and close files with fopen and fclose
- Text vs binary file modes and when to use each
- Reading and writing characters, strings, and formatted data
- Reading and writing binary records with fread and fwrite
- Moving the file pointer with fseek, ftell, and rewind
- Deleting, renaming, and checking files
- Error handling with perror, ferror, and feof
- Common file I/O bugs and why fclose matters
This page has 40 multiple choice questions on file handling in C. You'll find questions on opening and closing files, reading and writing text and binary data, moving the file pointer, deleting and renaming files, and handling errors. Each question comes with the correct answer and a short explanation in plain English, so you understand the "why" and not just the "what". File handling is heavily tested in college exams and interviews, especially the fread/fwrite and fseek families of functions.
File Basics & fopen/fclose
Q1. Which header file should be included in C for file manipulation operations?
Answer: a) #include <stdio.h>
All file operations in C (fopen, fclose, fread, fwrite, fgetc, etc.) are declared in stdio.h, along with the FILE type. stddef.h provides size_t and NULL but no file functions. "file.h" doesn't exist, and "iostream.h" is a C++ header. So stdio.h is always the correct answer.
Q2. Which function is used to open a file in C for both reading and writing?
Answer: b) fopen()
fopen() is the standard C library function that opens a file and returns a FILE* handle. Use mode "r+" or "w+" or "a+" for both reading and writing. open() and read()/write() are POSIX system calls that work with file descriptors (int), not FILE* — they're different from the C standard library and not portable to all C implementations.
Q3. The _______ function closes a file in C language.
Answer: c) fclose()
fclose(FILE *fp) is the standard function that flushes buffered data and releases the file handle. Its name follows the C convention of prefixing file functions with "f". None of the other options exist in standard C. close() (without the f) is a POSIX call that takes a file descriptor, not a FILE*. Always fclose what you fopen.
Q4. How do you check if a file was opened successfully in C?
Answer: a) By checking if fopen() returned NULL
fopen() returns NULL when it fails (file not found, no permission, disk full, etc.). The standard pattern is:
FILE *fp = fopen("data.txt", "r");
if (fp == NULL) { perror("data.txt"); return 1; }
Always check for NULL before using the FILE*. Forgetting this check is a common source of crashes in beginner C code.
Q5. What is the correct return type of the fopen() function in C?
Answer: b) FILE *
fopen() returns a FILE* pointer, which is an opaque handle to an open file. You can't inspect its contents directly — you just pass it back to other file functions (fgetc, fclose, etc.). This opaque-pointer design is a form of abstraction: the implementation is platform-specific, but your code stays portable. On failure, fopen() returns NULL.
Q6. Choose the correct syntax to open a file in write mode in C.
Answer: d) FILE *fptr = fopen("my_file.txt", "w");
"w" opens the file for writing in text mode, truncating it to zero length if it exists. Option a) opens for reading, b) opens for binary writing, and c) appends to the end (doesn't overwrite existing content). For "write mode" specifically, "w" is the answer. Choose "wb" only when you need to write raw bytes without newline translation.
Character I/O & Modes
Q7. Which function is used to read a single character from a file in C?
Answer: d) fgetc() or getc()
fgetc(FILE*) and getc(FILE*) both read one character (as an int, to distinguish EOF) from a file stream. fgetc is always a real function; getc may be implemented as a macro for speed. read() is a POSIX system call that takes a file descriptor, not a FILE*. fread is for reading blocks of data, not single characters. This distinction between FILE* functions and fd functions matters in interviews.
Q8. Which function is used to write a single character to a file in C?
Answer: c) fputc() or putc()
fputc(int ch, FILE*) and putc(int ch, FILE*) both write a single character. Like fgetc/getc, fputc is always a function, putc may be a macro. fwrite writes blocks (multiple bytes at once). write() is a POSIX system call. For single characters, fputc or putc is the answer.
Q9. Which mode should be used when opening a file to read a binary file in C?
Answer: b) "rb"
"rb" opens a file for reading in binary mode, disabling newline translation. On Unix-like systems this distinction doesn't matter (no translation happens anyway), but on Windows, "r" translates \r\n to \n and can corrupt binary data. Always use "rb" when reading non-text data (images, executables, serialized structs).
String & Line I/O
Q10. Which function is used to read a line from a file in C?
Answer: a) fgets()
fgets(char *buf, int size, FILE *fp) reads up to size-1 characters or a newline (whichever comes first) and null-terminates the result. The newline is included if it fits. None of the other functions are standard C. Note that fgets is also used for reading from stdin, since stdin is a FILE*.
Q11. Which function writes a string to a file in C?
Answer: c) fputs()
fputs(const char *s, FILE *fp) writes a null-terminated string to a file. It does not add a newline (unlike puts to stdout, which does). fwrite() also works but is for binary data blocks, not strings. For formatted text output with multiple values, use fprintf(). For a plain string, fputs is the answer.
Binary Files & fread/fwrite
Q12. Which function is used to write binary data to a file in C?
Answer: b) fwrite()
fwrite(const void *ptr, size_t size, size_t nmemb, FILE *fp) writes nmemb items of size bytes each. It's the standard way to write binary records (structs, arrays, etc.). write() is the POSIX system call that uses file descriptors. putdata and writebinary don't exist in C.
Q13. Which function is used to read binary data from a file in C?
Answer: b) fread()
fread(void *ptr, size_t size, size_t nmemb, FILE *fp) reads nmemb items of size bytes each into ptr. It's the mirror of fwrite and the standard way to read binary records back. Both fread and fwrite return the number of items actually transferred — always check this to detect a partial read (EOF or error).
Q14. What is the difference between text files and binary files in C?
Answer: c) Text files store human-readable characters; binary files store raw bytes
Text files hold characters that a human can read (numbers as ASCII digits, for example). Binary files hold raw bytes — the exact memory representation of a struct, array, or integer. Binary is more compact and faster, but not editable in a text editor. Text is portable and debuggable, but slower and less compact. Choose based on the use case.
File Positioning: fseek, ftell, rewind
Q15. How do you move the file pointer to a specific location in a file in C?
Answer: b) fseek()
fseek(FILE *fp, long offset, int whence) moves the file pointer by offset bytes from whence (SEEK_SET for start, SEEK_CUR for current, SEEK_END for end). It's the standard way to jump around in a file. seek() and lseek() exist in POSIX but work with file descriptors, not FILE*. move() and position() are not C functions.
Q16. Which function is used to check the end-of-file in C?
Answer: b) feof()
feof(FILE *fp) returns non-zero after a read attempt has hit EOF. Critically, it doesn't become true until after you try to read past the end — checking feof() before a read is a common bug that leads to double-reading the last character. The correct pattern is while ((c = fgetc(fp)) != EOF) { ... }.
Q17. Which function gets the current file pointer position in C?
Answer: c) ftell()
ftell(FILE *fp) returns the current position as a long integer (byte offset from the start). It's often paired with fseek to remember and restore positions, or used with fseek to the end to determine file size. Note: on some systems ftell's return value is only meaningful as an argument to fseek — not necessarily a true byte count, especially in text mode.
Q18. Which function moves the file pointer back to the beginning of the file?
Answer: a) rewind()
rewind(FILE *fp) is shorthand for fseek(fp, 0, SEEK_SET) plus a call to clearerr(fp) — it moves the pointer to the start and clears any error/EOF flags. This is handy for re-reading a file after you've consumed it. Only rewind() is a real C function; the others don't exist.
Q19. How do you determine the size of a file in C?
Answer: c) By seeking to end with fseek() and reading the position with ftell()
The standard idiom is:
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
rewind(fp);
No built-in "file size" function exists in standard C. size() and fsize() are not C functions. strlen() counts characters in a string (stops at '\0'), not bytes in a file. This idiom is essential for any program that pre-allocates buffers.
File Operations: Delete, Rename, Check
Q20. How do you delete a file in C?
Answer: b) remove()
remove(const char *filename) deletes a file. It returns 0 on success and non-zero on failure. On POSIX systems you can also call unlink(), but remove() is the portable C standard way. delete and erase are C++ keywords; deletefile doesn't exist. Remember to check the return value — remove can fail if the file is open or you lack permission.
Q21. Which function renames a file in C?
Answer: a) rename()
rename(const char *oldname, const char *newname) is the standard C function. It returns 0 on success. Note that rename can fail if the destination exists (on Windows) or if oldname doesn't exist. renamefile, moveto, and movefile are not C functions. On POSIX, rename can actually move a file to a different directory if the target is on the same file system.
Q22. Which function checks whether a file exists and if it's readable in C?
Answer: d) access() (POSIX; portable alternative is to try fopen)
Standard C has no portable "does this file exist?" function. On POSIX systems, access(path, F_OK) checks existence and access(path, R_OK) checks readability. The portable method is to try fopen() and check for NULL:
FILE *fp = fopen(path, "r");
if (fp) { /* exists */ fclose(fp); }
This works everywhere and is idiomatic C. Options a, b, c don't exist.
Error Handling & Buffering
Q23. What does the fflush() function do in C?
Answer: b) It forces buffered data to be written to the underlying file
When you write with fputc, fprintf, etc., the data goes into a buffer (in memory) first. fflush(FILE*) pushes that buffer to the actual file immediately. Useful when you want data visible to other processes before the file is closed, or in debugging (so that a crash doesn't lose your prints). fflush(NULL) flushes all output streams.
Q24. What does perror() do in C?
Answer: a) Prints a descriptive error message for the last failed system/library call
perror("custom message") prints "custom message: " followed by a human-readable description of the current errno. For example, if fopen fails because the file doesn't exist:
perror("data.txt");
prints "data.txt: No such file or directory".
It's the standard, portable way to report file errors and much better than just printing "error".
Q25. What is the purpose of ferror() in C?
Answer: b) It checks whether an error occurred on a stream
ferror(FILE *fp) returns non-zero if an error has occurred on the file stream. This lets you distinguish "hit end of file" (feof) from "hit an actual read/write error" (ferror). After handling the error, call clearerr(fp) to reset the flags so the stream can be used again. This pair is essential for robust file code.
Q26. What does SEEK_SET mean in fseek()?
Answer: c) Seek relative to the beginning of the file
SEEK_SET means "start counting from the beginning." So fseek(fp, 100, SEEK_SET) moves the pointer to byte offset 100 from the start. The other two are SEEK_CUR (from current) and SEEK_END (from end). These three constants are defined in stdio.h. This is the key to random access in files.
Q27. What does SEEK_END mean in fseek()?
Answer: b) Seek relative to the end of the file
SEEK_END means "start counting from the end." fseek(fp, 0, SEEK_END) moves to the end of the file (useful for getting file size with ftell). fseek(fp, -10, SEEK_END) moves 10 bytes before the end. Combined with SEEK_SET and SEEK_CUR, this gives you complete control over the file position.
Q28. What does SEEK_CUR mean in fseek()?
Answer: a) Seek relative to the current file position
SEEK_CUR means "start counting from the current position." fseek(fp, 5, SEEK_CUR) advances 5 bytes from wherever you are now. This is useful for skipping bytes, or moving backwards without knowing the absolute offset. It's the most common in streaming code — you can advance relative to the current reading point.
Q29. What is the maximum file size that can be handled in C on 32-bit systems by default?
Answer: a) About 2 GB
On traditional 32-bit systems, fseek/ftell use long (32-bit signed), which limits offsets to 2^31-1 bytes — about 2 GB. To handle larger files, use fseeko/ftello with off_t (POSIX, allows 64-bit offsets) or fopen64/fseeko64 (GNU extensions). This is why large-file support is a real portability concern in C.
Q30. Which function is used to read formatted data from a file in C?
Answer: a) fscanf()
fscanf(FILE *fp, const char *format, ...) reads formatted data (ints, floats, strings) from a file, just like scanf reads from stdin. Use it to parse structured text files (like CSVs or configuration files). fgets reads a whole line as a string; gets is unsafe and removed from C11. fscanf is more powerful but also trickier (return values, whitespace handling).
Q31. Which function writes formatted data to a file in C?
Answer: a) fprintf()
fprintf(FILE *fp, const char *format, ...) writes formatted output to a file, just like printf writes to stdout. It supports all printf format specifiers (%d, %s, %f, etc.). fputs writes a plain string without formatting; puts adds a newline and writes to stdout. For structured text output, fprintf is the way to go.
Q32. How do you copy one file to another in C?
Answer: d) Read from source, write to destination using fread/fwrite in a loop
C has no built-in file copy function. The standard pattern is:
char buf[4096];
size_t n;
while ((n = fread(buf, 1, sizeof(buf), src)) > 0)
fwrite(buf, 1, n, dst);
Read a chunk, write a chunk, repeat until EOF. This works for both text and binary. None of the other functions exist. You could also use sendfile() on Linux for efficient kernel-level copying.
Q33. Why must you close a file after you're done with it?
Answer: b) To flush buffers and release the file descriptor
If you don't fclose(), buffered data may not be written to disk (data loss on abnormal exit), and the OS file descriptor stays open. Run enough of these and you'll exhaust the process's file descriptor limit (usually 1024) — subsequent fopen calls start failing with "too many open files". The rule of thumb: every fopen needs a matching fclose, just like every malloc needs a free.
Q34. What happens if fopen() fails?
Answer: b) It returns NULL, and errno is set
fopen returns NULL on failure, and errno is set to a value that describes why (ENOENT for "file not found," EACCES for "permission denied," etc.). Use perror() or strerror(errno) to print a readable message. Never dereference a NULL FILE* — that's undefined behaviour and usually a crash. Always check for NULL immediately after fopen.
Q35. What is the difference between fgetc and getc in C?
Answer: c) getc may be implemented as a macro; fgetc is always a function
Both read one character from a stream. The difference is implementation: fgetc is guaranteed to be a real function, while getc may be a macro (allowing inlining for speed). As a macro, getc must not evaluate its argument more than once, so passing something like getc(fp++) is dangerous — use fgetc in that case. Functionally they're the same.
Q36. What is the difference between fputs and fprintf in C?
Answer: a) fputs writes a plain string; fprintf supports format specifiers
fputs(const char *s, FILE *fp) writes a string verbatim — no formatting. fprintf(FILE *fp, const char *fmt, ...) supports all printf-style formatting: fprintf(fp, "%d - %s\n", id, name). Use fputs when you have a fixed string; use fprintf when you need to substitute values. Both write to a FILE stream (not to stdout specifically), so option d is wrong.
Q37. Which function clears the error and EOF indicators on a file stream?
Answer: b) clearerr()
clearerr(FILE *fp) resets both the error indicator (set by ferror) and the EOF indicator (set by feof). It's useful after handling an error, when you want to try the same stream again. It does not flush buffers — for that use fflush. clearerr is often paired with fseek or rewind, since those calls don't reset the error state on their own (except rewind, which does).
Q38. Which mode opens a file for both reading and writing without truncating?
Answer: c) "r+"
"r+" opens an existing file for both reading and writing without truncating it. "w+" also opens for read/write but truncates first (destroying existing content). "a" and "a+" append instead of overwrite. Use "r+" when you want to modify parts of an existing file in place, and "w+" when you want to write a fresh file that you'll also read back.
Q39. Which of these modes would you use to append data to an existing file without losing its content?
Answer: c) "a"
"a" opens the file in append mode: existing content is preserved, and all writes go to the end. If the file doesn't exist, it's created. This is the mode for log files and any case where you want to add to existing data. "w" would truncate the file first. "r+" opens for read/write but doesn't move to end. Use "ab" if you're appending binary data.
Q40. Which of the following is the standard idiom for reading a file character-by-character until end of file?
Answer: b) while ((c = fgetc(fp)) != EOF) { /* ... */ }
Option b is the correct idiom. Option a is a classic bug — feof only becomes true after a read attempt hits EOF, so the loop body runs one extra time with the value EOF. Option d discards the character (doesn't store it in c), so you'd lose the value you just read. Option c is wrong in the other direction — feof stays false the first time. This pattern appears in countless real C programs.
Frequently Asked Questions
What is the difference between text and binary files in C?
Text files store data as human-readable characters (with newline translation on some systems). Binary files store raw bytes with no translation — faster and more compact, but not readable by humans. Use "r"/"w" for text and "rb"/"wb" for binary. On Unix there's no translation; on Windows text mode converts \r\n ↔ \n.
Why must I close a file after use?
fclose() flushes buffered data to disk and releases the file descriptor. If you forget to close, data may be lost (buffers not flushed on abnormal exit) or the OS may run out of file handles after many opens. It's the file equivalent of free(). Every fopen needs a matching fclose.
What happens if fopen() fails?
fopen() returns NULL, and errno is set. Always check for NULL before using the FILE pointer — dereferencing NULL leads to crashes. Use perror() to get a readable error message describing why the open failed. Common reasons: file doesn't exist ("r"), no permission, or disk full ("w").
What is the difference between fseek and rewind?
fseek() moves the file pointer to an arbitrary position (offset from SEEK_SET, SEEK_CUR, or SEEK_END). rewind() is a convenient shortcut that moves the pointer to the beginning and clears the error indicator. Use rewind when you just want to restart from the top; use fseek for anything else.
Why is ftell not reliable on all systems?
On some systems, text mode does newline translation (CRLF ↔ LF), which changes byte counts. ftell returns a value only meaningful when passed back to fseek — not necessarily a byte count. For reliable byte offsets, open files in binary mode ("rb"/"wb"). This matters when porting file code from Windows to Linux or vice versa.
💡 Tip: File handling is a favourite exam topic. Focus on these five things: the return value of fopen (NULL on failure), the while-fgetc-until-EOF idiom, the fseek/ftell file-size pattern, the difference between text and binary mode, and the correct placement of fclose. Get those right and you'll cover 80% of the questions you'll see.