Data Organization and File Operations
Understanding File Handling in C Programming
Instructor: Mohsin F. Dar
Assistant Professor
Cloud & Software Operations Cluster | SOCS
University of Petroleum and Energy Studies (UPES)
BTech First Semester - C Programming
What is Data Organization?
Definition
Data organization refers to the systematic arrangement and management of data for efficient storage, retrieval, and processing.
Why Do We Need Files?
Problem: Variables and arrays lose data when the program terminates.
Solution: Files provide permanent storage on secondary memory (hard disk, SSD).
Key Concept: Files enable data persistence beyond program execution, allowing data to be saved and retrieved across multiple program runs.
Types of Data Organization
1. Sequential Organization
Records are stored one after another in a specific order.
Example: Student records stored by roll number
Use: Processing all records, simple access
2. Random/Direct Organization
Records can be accessed directly without reading previous records.
Example: Database index files
Use: Quick access to specific records
3. Indexed Organization
Uses an index to locate records quickly.
Example: Phone directory
Use: Fast searching
4. Linked Organization
Records contain pointers to next records.
Example: Linked list implementation
Use: Dynamic data structures
File Operations in C
Basic File Operations
| Operation |
Description |
Function |
| Create |
Create a new file |
fopen() with "w" mode |
| Open |
Open existing file |
fopen() |
| Read |
Read data from file |
fscanf(), fgets(), fread() |
| Write |
Write data to file |
fprintf(), fputs(), fwrite() |
| Close |
Close the file |
fclose() |
File Pointer (FILE *)
What is a File Pointer?
A file pointer is a pointer to a structure of type FILE defined in stdio.h. It maintains information about the file being accessed.
FILE *fptr;
What FILE Pointer Contains:
- Current position: Where we are reading/writing
- Mode: Read, write, or append
- Buffer information: For efficient I/O
- Error indicators: To check file status
Important: Always check if file pointer is NULL after fopen() to ensure file opened successfully!
Opening a File: fopen()
Syntax
FILE *fopen(const char *filename, const char *mode);
File Opening Modes
| Mode |
Description |
File Must Exist? |
| "r" |
Read only |
Yes |
| "w" |
Write only (creates new/overwrites existing) |
No |
| "a" |
Append (add to end of file) |
No |
| "r+" |
Read and write |
Yes |
| "w+" |
Read and write (overwrites) |
No |
| "a+" |
Read and append |
No |
fopen() - Practical Example
#include <stdio.h>
int main() {
FILE *fptr;
// Opening file for writing
fptr = fopen("student.txt", "w");
// Check if file opened successfully
if (fptr == NULL) {
printf("Error opening file!\n");
return 1;
}
printf("File opened successfully!\n");
// Always close the file
fclose(fptr);
return 0;
}
Best Practice: Always check if fptr is NULL before performing file operations. This prevents program crashes and undefined behavior.
Writing to Files
1. fprintf() - Formatted Output
FILE *fptr = fopen("data.txt", "w");
fprintf(fptr, "Name: %s\n", "John");
fprintf(fptr, "Age: %d\n", 20);
fclose(fptr);
2. fputs() - Write String
FILE *fptr = fopen("data.txt", "w");
fputs("Hello, World!\n", fptr);
fputs("Welcome to C Programming\n", fptr);
fclose(fptr);
3. fputc() - Write Single Character
FILE *fptr = fopen("data.txt", "w");
fputc('A', fptr);
fputc('\n', fptr);
fclose(fptr);
Reading from Files
1. fscanf() - Formatted Input
FILE *fptr = fopen("data.txt", "r");
char name[50];
int age;
fscanf(fptr, "%s %d", name, &age);
printf("Name: %s, Age: %d\n", name, age);
fclose(fptr);
2. fgets() - Read String
FILE *fptr = fopen("data.txt", "r");
char line[100];
while (fgets(line, 100, fptr) != NULL) {
printf("%s", line);
}
fclose(fptr);
3. fgetc() - Read Single Character
FILE *fptr = fopen("data.txt", "r");
char ch;
while ((ch = fgetc(fptr)) != EOF) {
printf("%c", ch);
}
fclose(fptr);
Complete Example: Student Record System
#include <stdio.h>
int main() {
FILE *fptr;
char name[50];
int rollno, marks;
// Writing to file
fptr = fopen("students.txt", "w");
if (fptr == NULL) {
printf("Error!\n");
return 1;
}
fprintf(fptr, "101 Rahul 85\n");
fprintf(fptr, "102 Priya 92\n");
fprintf(fptr, "103 Amit 78\n");
fclose(fptr);
// Reading from file
fptr = fopen("students.txt", "r");
printf("Roll No\tName\tMarks\n");
printf("-------------------------\n");
while (fscanf(fptr, "%d %s %d", &rollno, name, &marks) != EOF) {
printf("%d\t%s\t%d\n", rollno, name, marks);
}
fclose(fptr);
return 0;
}
EOF and Error Handling
What is EOF?
EOF (End Of File) is a constant defined in stdio.h that indicates the end of file has been reached.
Error Handling Functions
| Function |
Purpose |
| feof(fptr) |
Returns non-zero if end of file reached |
| ferror(fptr) |
Returns non-zero if error occurred |
| perror() |
Prints error message |
FILE *fptr = fopen("data.txt", "r");
if (fptr == NULL) {
perror("Error"); // Prints: Error: No such file or directory
return 1;
}
Text Files vs Binary Files
Text Files
- Human-readable format
- Stores data as characters
- Larger file size
- Easy to edit
- Mode: "r", "w", "a"
fptr = fopen("data.txt", "w");
fprintf(fptr, "%d", 100);
Binary Files
- Machine-readable format
- Stores data in binary form
- Smaller file size
- Faster processing
- Mode: "rb", "wb", "ab"
fptr = fopen("data.bin", "wb");
int num = 100;
fwrite(&num, sizeof(int), 1, fptr);
Binary File Operations
fwrite() - Write Binary Data
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *fptr);
// Example
int numbers[] = {10, 20, 30, 40, 50};
FILE *fptr = fopen("data.bin", "wb");
fwrite(numbers, sizeof(int), 5, fptr);
fclose(fptr);
fread() - Read Binary Data
size_t fread(void *ptr, size_t size, size_t count, FILE *fptr);
// Example
int numbers[5];
FILE *fptr = fopen("data.bin", "rb");
fread(numbers, sizeof(int), 5, fptr);
fclose(fptr);
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
File Positioning Functions
Important Functions
| Function |
Description |
| fseek(fptr, offset, whence) |
Move file pointer to specific position |
| ftell(fptr) |
Returns current position of file pointer |
| rewind(fptr) |
Move file pointer to beginning |
fseek() Parameters
- SEEK_SET (0): Beginning of file
- SEEK_CUR (1): Current position
- SEEK_END (2): End of file
FILE *fptr = fopen("data.txt", "r");
fseek(fptr, 10, SEEK_SET); // Move 10 bytes from start
long pos = ftell(fptr); // Get current position
rewind(fptr); // Go back to start
File Positioning Demo
Demonstrating fseek(), ftell(), and rewind()
#include <stdio.h>
int main()
{
FILE *fp;
char ch;
fp = fopen("demo.txt", "w+"); // Open for reading + writing
if (fp == NULL) {
printf("Error opening file\n");
return 0;
}
// Writing some data into file
fputs("Hello File Positioning!", fp);
// 1. Move to 6th byte from beginning (after "Hello ")
fseek(fp, 6, SEEK_SET);
// 2. Show current pointer position
long pos = ftell(fp);
printf("Current position using ftell(): %ld\n", pos);
// 3. Read and display next character
ch = fgetc(fp);
printf("Character at position %ld: %c\n", pos, ch);
// 4. Move 5 bytes ahead from current position
fseek(fp, 5, SEEK_CUR);
pos = ftell(fp);
printf("New position after SEEK_CUR: %ld\n", pos);
// 5. Move pointer to beginning using rewind()
rewind(fp);
pos = ftell(fp);
printf("Position after rewind(): %ld\n", pos);
fclose(fp);
return 1;
}
Key Points:
fseek() moves the file pointer to a specific position
ftell() returns the current position of the file pointer
rewind() resets the file pointer to the beginning of the file
Common Mistakes to Avoid
❌ Mistake 1: Not Checking FILE Pointer
FILE *fptr = fopen("data.txt", "r");
fprintf(fptr, "Hello"); // CRASH if file doesn't exist!
✅ Correct Way
FILE *fptr = fopen("data.txt", "r");
if (fptr == NULL) {
printf("Error opening file!\n");
return 1;
}
fprintf(fptr, "Hello");
❌ Mistake 2: Forgetting to Close File
Always close files using fclose(fptr) to:
- Save buffered data
- Free system resources
- Prevent data corruption
Practical Application: Grade Management
#include <stdio.h>
struct Student {
int rollno;
char name[50];
float marks;
};
int main() {
FILE *fptr;
struct Student s;
// Writing student data
fptr = fopen("grades.dat", "wb");
if (fptr == NULL) {
printf("Error!\n");
return 1;
}
s.rollno = 101;
strcpy(s.name, "Alice");
s.marks = 89.5;
fwrite(&s, sizeof(struct Student), 1, fptr);
fclose(fptr);
// Reading student data
fptr = fopen("grades.dat", "rb");
fread(&s, sizeof(struct Student), 1, fptr);
printf("Roll: %d, Name: %s, Marks: %.2f\n",
s.rollno, s.name, s.marks);
fclose(fptr);
return 0;
}
Summary
Key Takeaways
- Files provide permanent storage for data beyond program execution
- FILE pointer is essential for all file operations
- Always check if file opened successfully (fptr != NULL)
- Different modes for different operations (r, w, a, etc.)
- Text files are human-readable, binary files are more efficient
- Always close files using fclose() to prevent data loss
- Error handling is crucial for robust programs
Remember: File handling is fundamental for real-world applications like databases, log files, configuration files, and data persistence.
What's Next?
In Our Next Lecture...
- Advanced file operations
- File management functions (rename, remove)
- Command line arguments with files
- Working with multiple files
- Introduction to memory management
Practice Exercises
- Create a program to store and retrieve employee records
- Write a program to copy contents from one file to another
- Develop a simple text editor using file operations
- Implement a student grade calculator with file storage
Thank You!
Questions?
Feel free to ask any questions about File Handling!
Mohsin F. Dar
Assistant Professor - SOCS | UPES
📧 Contact for clarifications