Files
Files
Introduction to Files in C
In C, files are used to store and retrieve data permanently. Unlike variables, the
data stored in files is not lost when the program ends.
To work with files, C uses a special data type called FILE, defined in the
<stdio.h> header.
File Pointer
FILE *fp;
a file pointer is a special pointer of type FILE* that is used to access and
manipulate files.This pointer is used with functions like fopen(), fclose(),
fread(), fwrite(), etc.It points to a structure that holds information about the
file (such as current position, mode, etc.).
File Types
1. Text Files
To open a file:
Modes:
Mode Meaning
fclose(fp);
Reading from Files
fgetc()
char ch = fgetc(fp);
fgets()
char str[100];
fgets(str, 100, fp);
fread()
Writing to Files
fputc()
fputc('A', fp);
fputs()
Writes a string:
fputs("Hello, world!", fp);
fwrite()
Example:
• Access any part of the file directly using file position pointer.
• Use fseek() and ftell() functions.
• Needed for binary files or when updating specific records.
int main() {
FILE *sourceFile, *destFile;
char ch;
• Explanation:
• fopen() opens both files: one for reading, one for writing.
int main() {
FILE *fp;
char ch;
fp = fopen("sample.txt", "r");
if (fp == NULL) {
return 1;
fseek(fp, 0, SEEK_SET);
ch = fgetc(fp);
ch = fgetc(fp);
ch = fgetc(fp);
fclose(fp);
1. From SEEK_SET:
Output: H (1st character)
2. From SEEK_CUR (10 chars ahead from 2nd position):
Output: Likely h or a depending on offset
3. From SEEK_END (-5):
Output: The 5th character before the file ends. For example: 'i' from "file."
Constants:
Constant Description
SEEK_SET Start from the beginning of the file. Offset is from byte 0.
struct Student {
char name[50];
int age;
};