A file is a collection of related data stored on a secondary storage device. In C, files are treated as a stream of bytes. They are primarily categorized based on how the data is stored and accessed.
Before performing any operation on a file, it must be opened, and after the work is done, it must be closed to free resources.
In C, all file operations use a special structure called FILE defined in stdio.h. We declare a pointer of this type to track the file.
FILE *fp;
Used to open a file. It returns the address of the file if successful, otherwise NULL.
fp = fopen("filename.txt", "mode");Used to close the file. It ensures all data is properly written (flushed) from the buffer to the disk.
fclose(fp);
Modes specify the purpose for which the file is being opened.
| Mode | Meaning | Description |
|---|---|---|
| "r" | Read | Opens an existing file for reading only. |
| "w" | Write | Creates a new file or overwrites an existing one. |
| "a" | Append | Adds data to the end of an existing file. |
| "r+" | Read/Write | Opens an existing file for both reading and writing. |
| "w+" | Write/Read | Creates a new file for both reading and writing. |
C distinguishes between two types of file formats:
Various functions are used to transfer data between the program and the file.
fprintf(fp, "Format", variables); - Writes formatted data to a file.fscanf(fp, "Format", &variables); - Reads formatted data from a file.EOF at the end of the file.A header file is a file with a .h extension that contains C function declarations and macro definitions. It allows you to share code across multiple source files.
mymath.h).#include "mymath.h".The preprocessor is a tool that processes the source code before it is passed to the compiler. Directives start with a # symbol.
Definition: A macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro.
Example: #define PI 3.14 (Object-like macro) or #define SQUARE(x) ((x)*(x)) (Function-like macro).
EOF (End of File) while reading character-by-character to avoid infinite loops.fp == NULL after fopen(). This demonstrates robust coding.#define MUL(a, b) a * b). If you call MUL(2+3, 4), it becomes 2 + 3 * 4 = 14 instead of 20. Correct: ((a)*(b)).Q: What is the return value of fclose()?
A: It returns 0 on success and EOF if an error occurs during closing.
Q: Why use binary files over text files?
A: Binary files are much faster for reading/writing complex data like structures and they take up less space on the disk.
Q: What is the difference between #include <file.h> and #include "file.h"?
A: Angle brackets <> search in system directories; double quotes "" search in the local project directory first.