- Opening files with fopen and its read/write modes
- Reading with fgetc, fgets, fscanf, and fread
- Writing with fputc, fputs, fprintf, and fwrite
- Moving through a file with fseek, ftell, and rewind
- Detecting end-of-file and errors with feof and ferror
- Error handling with errno, perror, and strerror
- Copy, rename, delete, and append operations
This page answers 20 of the most-asked file handling questions from C interviews and exams. It starts with opening and closing files, then moves through reading, writing, file position, and error handling, and ends with the common operations — copy, rename, delete, append, and binary I/O. Each answer is in plain English with a short code example you can use in interviews or in your own code. If you're preparing for a technical interview, pay close attention to Q2 (fopen modes), Q8 (feof vs ferror), and Q15 (fseek + ftell for file size) — these come up again and again.
Opening and closing files
Q1. How do you open a file in C?
Answer: Use fopen() from <stdio.h>. It returns a FILE* on success, or NULL on failure.
#include <stdio.h>
FILE *fp = fopen("data.txt", "r");
if (fp == NULL) {
perror("fopen"); /* prints the reason for failure */
return -1;
}
/* ... use fp ... */
fclose(fp);
The first argument is the filename (a path relative to the working directory, or absolute). The second is the mode — read, write, append, or one of the update forms. Always check for NULL — if the file doesn't exist or you don't have permission, fopen returns NULL and errno is set to the specific reason. Attempting to use the file handle without checking causes a crash.
Full tutorial: File Handling in C
Q2. What is the difference between "r" and "w" modes in file opening?
Answer: r opens an existing file for reading; w opens or creates a file for writing, truncating it first.
The full mode set:
- "r" — read. File must exist. Returns NULL if not.
- "w" — write. Creates the file if missing, truncates it to zero length if it exists.
- "a" — append. Creates if missing, writes at the end if it exists. Does not truncate.
- "r+" — read and write. File must exist. Doesn't truncate.
- "w+" — read and write. Creates or truncates.
- "a+" — read and append. Creates if missing.
Adding b after the mode opens the file in binary mode on systems that distinguish text and binary (Windows). On Unix-like systems the difference is mostly cosmetic. The common mistake is using "w" when you meant to append — that erases the existing file.
Full tutorial: Types of Files in C
Q3. How do you close a file in C?
Answer: Use fclose(). It flushes buffered writes, releases the FILE handle, and returns 0 on success or EOF on failure.
FILE *fp = fopen("data.txt", "w");
if (fp == NULL) { /* handle error */ }
fprintf(fp, "hello\n");
if (fclose(fp) != 0) {
perror("fclose"); /* rarely fails, but check anyway */
}
Why closing matters:
- Flushes the buffer: data written may sit in memory until the buffer fills or you close. If the program crashes before close, that data is lost.
- Releases the file handle: each open file uses a file descriptor. Operating systems limit how many you can have open at once.
- Signals completion: on some filesystems, close triggers final metadata updates.
If you absolutely must flush without closing, use fflush(fp). But still close when done.
Full tutorial: Operations in File Handling
Q4. How do you check if a file exists in C?
Answer: Use fopen in read mode and check for NULL, or use stat() from <sys/stat.h>.
/* Method 1 — simple check via fopen */
FILE *fp = fopen("data.txt", "r");
if (fp != NULL) {
printf("file exists\n");
fclose(fp);
} else {
printf("file not found\n");
}
/* Method 2 — stat gives more information */
#include <sys/stat.h>
struct stat st;
if (stat("data.txt", &st) == 0) {
printf("file exists, size = %ld bytes\n", st.st_size);
}
The fopen approach is quick and portable. It has a race condition — the file could be deleted between the check and the actual use — but for simple programs that's fine. The stat approach additionally tells you the size, permissions, and modification time. On Unix, access(path, F_OK) is another common way to check existence.
Full tutorial: File Examples in C
Reading and writing
Q5. How do you read from a file in C?
Answer: Four common functions — fgetc(), fgets(), fscanf(), and fread() — chosen by what you're reading.
- fgetc(fp) — reads one character. Returns the character as an
int, or EOF. - fgets(buf, size, fp) — reads up to
size-1chars or a newline. Returns the buffer, or NULL at EOF. - fscanf(fp, "%d", &n) — reads formatted input. Like
scanfbut from a file. - fread(buf, size, count, fp) — reads
countitems ofsizebytes each. Best for binary data.
/* Read the whole file one line at a time */
char line[256];
FILE *fp = fopen("data.txt", "r");
while (fgets(line, sizeof(line), fp) != NULL) {
printf("%s", line);
}
fclose(fp);
For text with structure (numbers, words), fscanf is direct. For line-oriented text, fgets is safer — it won't read past a newline, and it lets you limit buffer size. For binary data, use fread.
Full tutorial: File Examples in C
Q6. How do you write to a file in C?
Answer: Open the file in a write mode, then use fputc, fputs, fprintf, or fwrite. Close with fclose to flush.
FILE *fp = fopen("data.txt", "w");
if (fp == NULL) { /* handle error */ }
fprintf(fp, "Name: %s\n", "Ram");
fputs("Hello, world\n", fp);
fputc('!', fp);
fclose(fp); /* flushes the buffer to disk */
The four functions mirror the four read functions:
- fputc(c, fp) — writes one character.
- fputs(s, fp) — writes a string.
- fprintf(fp, fmt, ...) — formatted write.
- fwrite(buf, size, count, fp) — writes raw bytes (for structs, arrays, binary data).
Always check fclose's return value — it can fail if the disk is full or the file was on a network that dropped. A failed close means the writes may not have hit the disk.
Full tutorial: File Examples in C
Q7. How do you append data to an existing file in C?
Answer: Open the file in append mode — "a" or "a+". Writes go to the end without erasing existing content.
FILE *fp = fopen("log.txt", "a"); /* append mode */
if (fp == NULL) { /* handle error */ }
fprintf(fp, "Log entry: %s\n", "user logged in");
fclose(fp);
The key difference from "w": append mode does not truncate the file. Every write is forced to the end, regardless of where the position indicator sits. This is the safe mode for log files. The "a+" variant additionally allows reading.
Full tutorial: Update File in C
Q8. How do you read and write binary files in C?
Answer: Use fread() and fwrite(), with the file opened in a binary mode ("rb", "wb", "rb+").
struct Record {
int id;
char name[32];
float score;
};
/* Write */
FILE *out = fopen("data.bin", "wb");
struct Record r = {1, "Ram", 88.5};
fwrite(&r, sizeof(r), 1, out);
fclose(out);
/* Read */
FILE *in = fopen("data.bin", "rb");
struct Record r2;
fread(&r2, sizeof(r2), 1, in);
fclose(in);
Binary files store raw bytes — exactly the in-memory representation — so they're fast and compact. fread and fwrite handle fixed-size records perfectly. Text mode on Windows translates \n to \r\n and back, which can corrupt binary data — that's why binary files must be opened with "b" appended to the mode. Use text mode (fprintf/fscanf) for human-readable data and binary mode (fread/fwrite) for structs, arrays, and raw bytes.
Full tutorial: Binary Files in C
File position with fseek and ftell
Q9. What is the purpose of the fseek() function in file handling?
Answer: fseek() moves the file position indicator to a specific byte offset, so the next read or write starts there.
/* Move to byte 100 of the file */ fseek(fp, 100, SEEK_SET); /* SEEK_SET = from start */ /* Move 50 bytes forward from current position */ fseek(fp, 50, SEEK_CUR); /* SEEK_CUR = from current */ /* Move 10 bytes back from end of file */ fseek(fp, -10, SEEK_END); /* SEEK_END = from end */
The three constants define where the offset is measured from. SEEK_SET is absolute — useful when you know the byte offset. SEEK_CUR is relative to the current position. SEEK_END is relative to the file's end — useful for jumping to the last bytes. Returns 0 on success, non-zero on failure (e.g., trying to seek before the start). Use ftell() to read the current position.
Full tutorial: Operations in File Handling
Q10. What is the purpose of the rewind() function in file handling?
Answer: rewind(fp) resets the file position to the beginning and clears the error indicator.
/* Read once */
char buf[100];
fgets(buf, 100, fp);
printf("%s", buf);
/* Go back to start and read again */
rewind(fp);
fgets(buf, 100, fp);
printf("%s", buf); /* same first line */
rewind(fp) is essentially fseek(fp, 0, SEEK_SET) plus clearerr(fp) — it rewinds AND clears any pending error or EOF flag. This makes it slightly more useful than a plain fseek, since after a failed read at EOF, a subsequent operation may need the EOF flag cleared to work correctly.
Full tutorial: Operations in File Handling
Q11. How do you check the size of a file in C?
Answer: Use fseek(fp, 0, SEEK_END) to move to the end, then ftell(fp) returns the byte offset — which equals the file size.
FILE *fp = fopen("data.txt", "rb");
if (fp == NULL) { /* handle error */ }
fseek(fp, 0, SEEK_END); /* jump to end */
long size = ftell(fp); /* offset = size in bytes */
rewind(fp); /* back to start */
printf("File size: %ld bytes\n", size);
fclose(fp);
This works for regular files but not for pipes, sockets, or stdin — those don't have a fixed size. On Windows, _ftelli64 is needed for files larger than 2 GB. On Unix, stat() gives the size directly (st.st_size) without opening the file — often the cleaner choice for just asking "how big is this file?".
Full tutorial: Operations in File Handling
End-of-file and error handling
Q12. What is the difference between feof() and ferror()?
Answer: feof() tests the end-of-file indicator; ferror() tests the error indicator. Both return non-zero if the flag is set.
FILE *fp = fopen("data.txt", "r");
int c;
while ((c = fgetc(fp)) != EOF) {
putchar(c);
}
if (feof(fp)) printf("\n[reached end normally]\n");
if (ferror(fp)) printf("\n[read error occurred]\n");
fclose(fp);
Both flags are sticky — they stay set until you call clearerr(fp) or rewind(fp). That means you can't just check feof after every fgetc to know you're at the end — it only becomes true after you've tried to read past the last byte. The correct pattern is to check the function's return value for EOF or NULL, then use feof or ferror to determine why the read stopped.
Full tutorial: Operations in File Handling
Q13. How do you handle end-of-file conditions in C file handling?
Answer: Check the return value of the read function, not feof(). feof() only becomes true after the failed read.
/* WRONG - reads one extra time */
while (!feof(fp)) {
int c = fgetc(fp);
putchar(c); /* prints garbage at the end */
}
/* RIGHT - check the read itself */
int c;
while ((c = fgetc(fp)) != EOF) {
putchar(c);
}
This is one of the most common file-handling bugs. feof(fp) is false while there's still a byte to read, but becomes true only after you've attempted to read past the last byte. So while (!feof(fp)) runs one extra iteration, and the body prints a garbage value or NULL. The idiomatic pattern is to check the read function's return value — fgetc returns EOF, fgets returns NULL, fread returns fewer than expected — which tells you directly that the file is done.
Full tutorial: Operations in File Handling
Q14. How do you handle errors while working with files in C?
Answer: Check return values, then use perror() or strerror(errno) to get a readable error message.
#include <stdio.h>
#include <errno.h>
#include <string.h>
FILE *fp = fopen("missing.txt", "r");
if (fp == NULL) {
/* Option 1 — perror prints "fopen: " */
perror("fopen");
/* Option 2 — strerror gives just the reason */
printf("Error: %s\n", strerror(errno));
return -1;
}
On failure, C library functions set the global variable errno to a number identifying the error (ENOENT for "no such file", EACCES for "permission denied", etc.). perror prints a message combining your prefix and the reason. strerror(errno) gives you just the reason as a string, for custom formatting. Check errno immediately after the failed call — any subsequent library call may overwrite it.
Full tutorial: Operations in File Handling
Copying, renaming, deleting, and appending
Q15. How do you copy the contents of one file to another in C?
Answer: Open source in read mode, destination in write mode, then read a character or block from source and write to destination in a loop.
FILE *src = fopen("source.txt", "rb");
FILE *dst = fopen("dest.txt", "wb");
if (src == NULL || dst == NULL) { /* handle */ }
int c;
while ((c = fgetc(src)) != EOF) {
fputc(c, dst);
}
fclose(src);
fclose(dst);
For small files, character-by-character is fine. For larger files, a block loop with fread and fwrite is much faster — you avoid the function call overhead for every byte:
char buffer[4096];
size_t n;
while ((n = fread(buffer, 1, sizeof(buffer), src)) > 0) {
fwrite(buffer, 1, n, dst);
}
Open in binary mode for byte-exact copying. Text mode can silently translate line endings, which may not be what you want if the source is binary data disguised as text.
Full tutorial: Copy Files in C
Q16. How do you rename a file in C?
Answer: Use rename() from <stdio.h>. It returns 0 on success, non-zero on failure.
if (rename("old.txt", "new.txt") == 0) {
printf("renamed successfully\n");
} else {
perror("rename");
}
The old file must exist and the new name must not already exist on most systems. If the destination exists, the behaviour is platform-dependent — POSIX systems overwrite it, Windows may fail. The rename can fail across filesystems (moving from one mount point to another) — for those cases, you must copy then delete.
Full tutorial: Update File in C
Q17. How do you delete a file in C?
Answer: Use remove() from <stdio.h>. It returns 0 on success, non-zero on failure.
if (remove("temp.txt") == 0) {
printf("deleted\n");
} else {
perror("remove");
}
remove() deletes a file (or an empty directory, on POSIX systems). It requires that you have permission to delete the file and that the file is not currently open by any process. Once deleted, the file is gone — there is no recycle bin in standard C. For safety in real applications, consider asking the user to confirm before calling this.
Full tutorial: Update File in C
Q18. How do you create a temporary file in C?
Answer: Use tmpfile() — it creates an unnamed temporary file that's automatically deleted when you close it or the program exits.
FILE *tmp = tmpfile();
if (tmp == NULL) { /* handle error */ }
fprintf(tmp, "temporary data\n");
rewind(tmp);
char line[100];
fgets(line, sizeof(line), tmp);
printf("%s", line);
fclose(tmp); /* file is deleted automatically */
tmpfile() opens the file in binary update mode ("wb+") and it disappears the moment the handle closes. Perfect for storing scratch data without leaving files behind. If you need a named temporary file (e.g., to pass the path to another program), use mkstemp() on POSIX or tmpnam() (deprecated — has security issues) on older systems.
Full tutorial: Operations in File Handling
Q19. How do you set file permissions in C?
Answer: Use chmod() from <sys/stat.h> on POSIX systems. Standard C alone cannot change permissions.
#include <sys/stat.h>
/* Set rw-r--r-- (owner read/write, others read) */
if (chmod("data.txt", S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) == 0) {
printf("permissions set\n");
} else {
perror("chmod");
}
The permission bits are specified as a bitmask. Common ones: S_IRUSR (owner read), S_IWUSR (owner write), S_IXUSR (owner execute), and the analogous S_I*GRP and S_I*OTH for group and others. Octal notation (0644, 0755) is a shorthand the shell uses; in C the flags are clearer. This is not available on Windows in standard C — Windows uses ACLs, which you access via Win32 API instead.
Full tutorial: Operations in File Handling
Q20. How do you read a directory's contents in C?
Answer: Use opendir(), readdir(), and closedir() from <dirent.h> on POSIX systems.
#include <dirent.h>
#include <stdio.h>
DIR *dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
opendir returns a DIR* stream (or NULL on failure). readdir returns one entry at a time, or NULL at the end. closedir releases the handle. Standard C itself has no directory API — this is POSIX. On Windows, use FindFirstFile / FindNextFile. The readdir results always include . and .. — filter them out if you only want real files.
Full tutorial: File Handling in C
Frequently Asked Questions
What is the difference between text mode and binary mode in C?
Text mode may translate line endings — on Windows, \n becomes \r\n on write and is converted back on read. Binary mode does no translation — bytes are read and written exactly as they are. Use text mode for human-readable files (logs, configs) and binary mode for structs, images, and any raw bytes. Forgetting the "b" in the mode when reading binary data can silently corrupt it.
What happens if you forget to close a file?
The program leaks a file descriptor, and any buffered writes may be lost if the program exits abnormally. On exit, most operating systems will close the file and flush the buffer — but relying on this is fragile, especially if the program crashes. Always close every file you open, ideally with the file handle and the close call in the same function.
Can you open the same file twice in one program?
Yes — you can have multiple FILE handles open on the same file. But each handle has its own position indicator, so writing through one and reading through another can cause confusing results if you aren't careful to flush. If you need to read and write the same file, use a single handle opened with "r+" or "w+".
What's the difference between fflush() and fclose()?
fflush(fp) writes any buffered data to the file but keeps the handle open — you can keep reading or writing. fclose(fp) flushes AND releases the handle, after which the FILE pointer is invalid. Use fflush when you need data on disk immediately (logs, before a crash-prone operation), but still close the file when you're done.
How do you read a file line by line when lines have unknown length?
fgets(buf, size, fp) reads up to size-1 characters or up to a newline, whichever comes first — so it's safe for any length. If a line is longer than the buffer, fgets returns a partial line, and the next fgets continues from where it left off. Alternatively, use the POSIX getline() function, which allocates the buffer automatically and handles arbitrarily long lines.
💡 Tip: File handling questions in interviews come down to four things: knowing the fopen modes (r, w, a, and the '+' and 'b' variants), understanding that fread/fwrite work on binary blocks and fscanf/fprintf on formatted text, being able to explain the feof trap, and knowing how to check errors with perror and errno. If you can explain those four fluently, you're ready for any file handling question.