Introduction to File Handling in C #
In C programming, there are two main ways to persist data:
- Files (stored on disk)
- Databases (structured data storage)
This tutorial focuses on file I/O (Input/Output) using the C Standard Library.
Text Files vs. Binary Files in C #
- Text files: store characters in readable form (ASCII, Unicode). Example:
.txt
files. - Binary files: store raw data not directly readable by humans. Example: executables, images, audio files.
Opening and Closing Files in C (fopen, fclose) #
fopen() – Open a File #
FILE *fopen(const char *path, const char *mode);
path
: file name or path (e.g.,"./file.txt"
)mode
: read, write, or append- Returns: file stream pointer on success, or
NULL
if failed
Common File Modes in C #
Mode | Meaning | Behavior |
---|---|---|
r | Read only | File must exist, read from start |
w | Write only | Creates or overwrites file |
a | Append only | Creates if not exists, writes at end |
r+ | Read/Write | File must exist, read & write from start |
w+ | Write/Read | Creates or overwrites file |
a+ | Append/Read | Creates if not exists, writes at end, reads from start |
fclose() – Close a File #
int fclose(FILE *fp);
- Closes an open file stream
- Returns
0
on success,EOF
on failure
Basic Steps for File I/O in C #
- Declare a file pointer
- Open the file with
fopen()
- Perform operations (read/write)
- Close the file with
fclose()
#include <stdio.h>
int main() {
FILE *fp = NULL;
fp = fopen("./1.txt", "r"); // open file for reading
if (fp == NULL) {
printf("Failed to open file!\n");
return 1;
}
// perform file operations here...
fclose(fp);
fp = NULL;
return 0;
}
Formatted File I/O in C (fprintf, fscanf) #
Writing to a File with fprintf #
int fprintf(FILE *stream, const char *format, ...);
Example:
#include <stdio.h>
int main() {
FILE *fp = fopen("./test.txt", "w+");
if (fp == NULL) {
printf("File open error!\n");
return 1;
}
fprintf(fp, "%s %d", "Score", 100); // write "Score 100" to file
fclose(fp);
return 0;
}
Reading from a File with fscanf #
int fscanf(FILE *stream, const char *format, ...);
Example:
#include <stdio.h>
int main() {
FILE *fp = fopen("./test.txt", "r");
if (fp == NULL) {
printf("File open error!\n");
return 1;
}
char str[100];
int num;
fscanf(fp, "%s %d", str, &num);
printf("Read: %s %d\n", str, num);
fclose(fp);
return 0;
}
Binary File I/O in C (fwrite, fread) #
Writing Binary Data with fwrite #
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);
Example:
#include <stdio.h>
int main() {
FILE *fp = fopen("./bin.dat", "w+");
if (fp == NULL) return 1;
int a[5] = {10, 20, 30, 40, 50};
fwrite(a, sizeof(int), 5, fp); // write array to file
fclose(fp);
return 0;
}
Reading Binary Data with fread #
size_t fread(void *ptr, size_t size, size_t count, FILE *stream);
Example:
#include <stdio.h>
int main() {
FILE *fp = fopen("./bin.dat", "r");
if (fp == NULL) return 1;
int buffer[5];
fread(buffer, sizeof(int), 5, fp); // read data into buffer
for (int i = 0; i < 5; i++) {
printf("%d ", buffer[i]);
}
fclose(fp);
return 0;
}
Output:
10 20 30 40 50
File Positioning in C (fseek, ftell) #
Sometimes you need to move around inside a file instead of reading sequentially.
fseek() – Set File Position #
int fseek(FILE *stream, long offset, int whence);
SEEK_SET
: from beginningSEEK_CUR
: from current positionSEEK_END
: from end
Examples:
fseek(fp, 8, SEEK_SET); // move 8 bytes from start
fseek(fp, -12, SEEK_END); // move 12 bytes back from end
ftell() – Get File Position #
long ftell(FILE *stream);
Example:
#include <stdio.h>
int main() {
FILE *fp = fopen("./bin.dat", "r");
if (fp == NULL) return 1;
fseek(fp, 8, SEEK_SET);
long pos = ftell(fp);
printf("Current position: %ld\n", pos);
fclose(fp);
return 0;
}
Conclusion #
With these C standard library functions, you can:
- Open and close files (
fopen
,fclose
) - Read and write text with formatting (
fprintf
,fscanf
) - Read and write raw binary data (
fread
,fwrite
) - Control file positions (
fseek
,ftell
)
These file handling functions form the foundation of data persistence in C programming.