File I/O
Duration: 50 min
File I/O allows you to read from and write to files. C provides functions for opening, closing, reading, and writing files. Understanding file operations is essential for working with persistent data.
Opening and Closing Files
#include <stdio.h>
int main() {
// Open file for writing
FILE *file = fopen("data.txt", "w");
if (file == NULL) {
printf("Error opening file\n");
return 1;
}
// Use the file
fprintf(file, "Hello, File!\n");
// Close the file
fclose(file);
return 0;
}File Modes
#include <stdio.h>
int main() {
// "r" - Read (file must exist)
// "w" - Write (creates or truncates file)
// "a" - Append (creates or appends to file)
// "r+" - Read and write
// "w+" - Write and read (truncates)
// "a+" - Append and read
FILE *file = fopen("example.txt", "w");
if (file != NULL) {
fprintf(file, "Line 1\n");
fprintf(file, "Line 2\n");
fclose(file);
}
return 0;
}Writing to Files
#include <stdio.h>
int main() {
FILE *file = fopen("output.txt", "w");
if (file == NULL) {
printf("Error opening file\n");
return 1;
}
// fprintf: formatted write
fprintf(file, "Name: %s\n", "Alice");
fprintf(file, "Age: %d\n", 25);
fprintf(file, "Score: %.2f\n", 95.5);
// fputs: write string
fputs("End of file\n", file);
fclose(file);
return 0;
}Reading from Files
#include <stdio.h>
int main() {
FILE *file = fopen("input.txt", "r");
if (file == NULL) {
printf("Error opening file\n");
return 1;
}
char line[100];
// fgets: read line
while (fgets(line, sizeof(line), file) != NULL) {
printf("%s", line);
}
fclose(file);
return 0;
}Reading Formatted Data
#include <stdio.h>
int main() {
FILE *file = fopen("data.txt", "r");
if (file == NULL) {
printf("Error opening file\n");
return 1;
}
char name[50];
int age;
float score;
// fscanf: formatted read
while (fscanf(file, "%s %d %f", name, &age, &score) == 3) {
printf("Name: %s, Age: %d, Score: %.2f\n", name, age, score);
}
fclose(file);
return 0;
}Binary File Operations
#include <stdio.h>
typedef struct {
int id;
char name[50];
float salary;
} Employee;
int main() {
// Write binary data
FILE *file = fopen("employees.bin", "wb");
Employee emp1 = {1, "Alice", 50000.0};
Employee emp2 = {2, "Bob", 60000.0};
// fwrite: write binary data
fwrite(&emp1, sizeof(Employee), 1, file);
fwrite(&emp2, sizeof(Employee), 1, file);
fclose(file);
// Read binary data
file = fopen("employees.bin", "rb");
Employee emp;
// fread: read binary data
while (fread(&emp, sizeof(Employee), 1, file) == 1) {
printf("ID: %d, Name: %s, Salary: %.2f\n",
emp.id, emp.name, emp.salary);
}
fclose(file);
return 0;
}File Positioning
#include <stdio.h>
int main() {
FILE *file = fopen("data.txt", "r");
if (file == NULL) {
printf("Error opening file\n");
return 1;
}
// ftell: get current position
printf("Current position: %ld\n", ftell(file));
// fseek: move to position
fseek(file, 0, SEEK_END); // Go to end
long size = ftell(file);
printf("File size: %ld bytes\n", size);
fseek(file, 0, SEEK_SET); // Go to beginning
// SEEK_SET - beginning
// SEEK_CUR - current position
// SEEK_END - end
fclose(file);
return 0;
}Practical Example: Student Records
#include <stdio.h>
#include <string.h>
typedef struct {
int id;
char name[50];
float gpa;
} Student;
int main() {
FILE *file = fopen("students.txt", "w");
// Write student records
Student students[] = {
{101, "Alice", 3.8},
{102, "Bob", 3.5},
{103, "Carol", 3.9}
};
for (int i = 0; i < 3; i++) {
fprintf(file, "%d %s %.2f\n",
students[i].id,
students[i].name,
students[i].gpa);
}
fclose(file);
// Read and display
file = fopen("students.txt", "r");
Student s;
while (fscanf(file, "%d %s %f", &s.id, s.name, &s.gpa) == 3) {
printf("ID: %d, Name: %s, GPA: %.2f\n", s.id, s.name, s.gpa);
}
fclose(file);
return 0;
}Quiz 1: File Modes
❓ What does the "w" mode do when opening a file?
Quiz 2: fopen Return Value
❓ What does fopen return if it fails to open a file?
Quiz 3: fprintf
❓ What does fprintf do?
Quiz 4: fread and fwrite
❓ What is the purpose of fread and fwrite?
Quiz 5: fseek
❓ What does SEEK_END do in fseek?