Introduction to File Handling in C Programming
File Handling in C Programming
Introduction to File Handling in C Programming
File handling in C programming is used to store data permanently in files instead of temporary memory (RAM). It allows you to create, read, write, and update files.
File handling in C programming is important for building real-world applications like data storage systems, logs, and reports.
What is File Handling in C Programming
File handling refers to performing operations on files such as creating, opening, reading, writing, and closing files.
In C programming, files are handled using pointers of type FILE.
File Pointer in C Programming
A file pointer is used to refer to a file.
Syntax
Steps for File Handling in C Programming
Basic Steps
- Declare file pointer
- Open file
- Perform operations (read/write)
- Close file
Opening a File in C Programming
Files are opened using fopen() function.
Syntax
Common File Modes
"r"→ Read"w"→ Write (overwrite)"a"→ Append"r+"→ Read and write
Example: Create and Write to File
int main() {
FILE *fp;
fp = fopen(“data.txt”, “w”);
fprintf(fp, “Hello File Handling”);
fclose(fp);
return 0;
}
Example: Read from File
int main() {
FILE *fp;
char ch;
fp = fopen(“data.txt”, “r”);
while((ch = fgetc(fp)) != EOF) {
printf(“%c”, ch);
}
fclose(fp);
return 0;
}
Example: Append Data to File
int main() {
FILE *fp;
fp = fopen(“data.txt”, “a”);
fprintf(fp, “\nNew Line Added”);
fclose(fp);
return 0;
}
Important File Functions in C Programming
Common Functions
fopen()→ Open filefclose()→ Close filefprintf()→ Write formatted datafscanf()→ Read formatted datafgetc()→ Read characterfputc()→ Write character
File Handling with User Input
int main() {
FILE *fp;
char name[20];
printf(“Enter name: “);
scanf(“%s”, name);
fp = fopen(“user.txt”, “w”);
fprintf(fp, “%s”, name);
fclose(fp);
return 0;
}
Why File Handling is Important
Key Benefits
- Permanent data storage
- Data sharing between programs
- Useful for large applications
- Helps in database-like systems
Common Mistakes
Avoid These Errors
- Not checking file open success
- Forgetting to close file
- Wrong file mode usage
Best Practice: Check File Open
printf(“File not opened”);
}
Start Learning C Programming
Practice file handling programs to build real-world applications in C programming.
Summary
File handling in C programming allows storing and managing data in files. It is essential for building practical and data-driven applications.
FAQs
What is file handling in C programming?
It is used to store and manage data in files.
What is FILE in C?
It is a data type used for file operations.
What is fopen()?
It is used to open a file.
Why close file?
To free resources and save data.



