File Handling Programs in C Programming
File Handling Programs in C Programming
Introduction to File Handling Programs in C Programming
File handling programs in C programming help you apply concepts like reading, writing, and updating files in real-world scenarios.
Practicing file handling programs in C programming improves your understanding of file operations and data management.
Program 1: Write and Read Data from File
int main() {
FILE *fp;
char data[50];
// Writing to file
fp = fopen(“file.txt”, “w”);
fprintf(fp, “Hello C Programming”);
fclose(fp);
// Reading from file
fp = fopen(“file.txt”, “r”);
fgets(data, sizeof(data), fp);
printf(“Data: %s”, data);
fclose(fp);
return 0;
}
Program 2: Copy Data from One File to Another
int main() {
FILE *fp1, *fp2;
char ch;
fp1 = fopen(“source.txt”, “r”);
fp2 = fopen(“dest.txt”, “w”);
while((ch = fgetc(fp1)) != EOF) {
fputc(ch, fp2);
}
fclose(fp1);
fclose(fp2);
printf(“File copied successfully”);
return 0;
}
Program 3: Count Characters in a File
int main() {
FILE *fp;
char ch;
int count = 0;
fp = fopen(“file.txt”, “r”);
while((ch = fgetc(fp)) != EOF) {
count++;
}
printf(“Total characters: %d”, count);
fclose(fp);
return 0;
}
Program 4: Append Data to File
int main() {
FILE *fp;
fp = fopen(“file.txt”, “a”);
fprintf(fp, “\nNew data added”);
fclose(fp);
return 0;
}
Program 5: Store and Retrieve Structure Data
struct Student {
int id;
float marks;
};
int main() {
FILE *fp;
struct Student s1 = {1, 90.5}, s2;
// Write structure
fp = fopen(“student.dat”, “wb”);
fwrite(&s1, sizeof(s1), 1, fp);
fclose(fp);
// Read structure
fp = fopen(“student.dat”, “rb”);
fread(&s2, sizeof(s2), 1, fp);
printf(“ID: %d\n”, s2.id);
printf(“Marks: %.2f”, s2.marks);
fclose(fp);
return 0;
}
Program 6: Count Lines in a File
int main() {
FILE *fp;
char ch;
int lines = 0;
fp = fopen(“file.txt”, “r”);
while((ch = fgetc(fp)) != EOF) {
if(ch == ‘\n’) {
lines++;
}
}
printf(“Total lines: %d”, lines + 1);
fclose(fp);
return 0;
}
Key Concepts Covered
Important Topics
- File reading and writing
- Copying files
- Counting data
- Appending content
- Binary file handling
Advantages of Practicing File Programs
Key Benefits
- Real-world application
- Strong file handling skills
- Better problem-solving
- Useful in projects
Start Learning C Programming
Practice file handling programs regularly to master file operations in C programming.
Summary
File handling programs in C programming help you understand real-world use cases of file operations like reading, writing, copying, and storing data.
FAQs
What are file handling programs in C programming?
Programs that perform operations on files.
Why practice file programs?
To understand real-world applications.
Which functions are commonly used?
fopen, fclose, fprintf, fscanf, fread, fwrite.
Can we store structures in files?
Yes, using binary file handling.



