File handling in C allows you to open, read, write, and edit files. You can use functions like fopen(), fclose(), fread(), fwrite(), fprintf(), and fscanf() to manage files. C works with text and binary files. In this tutorial, you will learn how to open files, write and read data, and close them properly. Knowing how to handle files helps you save and use data in C programs.
Contents:
- What is File Handling in C?
- Types of Files in C
- File Operations in C
- Opening and Closing a File (Using fopen() and fclose()) in C
- Writing to a File (Using fprintf() and fputs()) in C
- Reading from a File in C (Using fscanf() and fgets()) in C
- Writing and Reading Binary Data (Using fwrite() and fread()) in C
- Renaming and Deleting a File in C
- File Handling Functions in C
- File Pointers in C
- Error Handling in File Operations in C
- FAQs on File Handling in C
What is File Handling in C?
File handling in C allows a program to create, open, read, write, and close files stored on a disk. It enables persistent data storage beyond the program’s execution, unlike variables that lose data after the program ends.
Why Use File Handling?
File handling is important for several reasons:
- Storing data permanently: You can save data for future use.
- Handling large data: It helps manage large amounts of data efficiently.
- Working with structured data: You can read and write data like logs, records, or settings.
- Exchanging data: It allows different programs to share data.
Types of Files in C
In C, files are categorized into two main types:
1. Text Files
These files contain human-readable characters and are stored in ASCII format. They can be opened and edited with a text editor.
Characteristics:
- Stores data as plain text.
- Each line ends with a newline (\n) character.
- Slower access speed due to formatting and conversion.
- Takes more storage space than binary files.
Example – Writing to a Text File
#include <stdio.h> int main() { FILE *file = fopen("quiz.txt", "w"); // Open file in write mode if (file == NULL) { printf("Error opening file!\n"); return 1; } fprintf(file, "Sanfoundry C Programming Quiz\n"); fprintf(file, "This is a text file example.\n"); fclose(file); // Close the file printf("Text file created successfully.\n"); return 0; }
The program creates “quiz.txt” and writes two lines using fprintf(). The file stores the content as plain text.
2. Binary Files
Binary files store data in raw binary format (0s and 1s). They are not human-readable and require a program to interpret their content.
Characteristics:
- Stores data in machine-readable format.
- Faster read/write operations compared to text files.
- Uses less storage space as no conversions occur.
- Suitable for storing images, audio, video, and structured data.
Example – Writing to a Binary File
#include <stdio.h> struct Quiz { int id; char name[20]; }; int main() { struct Quiz q = {101, "C Basics"}; FILE *file = fopen("quiz.bin", "wb"); // Open file in binary write mode if (file == NULL) { printf("Error opening file!\n"); return 1; } fwrite(&q, sizeof(q), 1, file); // Write struct to binary file fclose(file); // Close the file printf("Binary file created successfully.\n"); return 0; }
Creates a binary file named “quiz.bin”. Uses fwrite() to store a struct Quiz in raw binary format.
File Operations in C
File operations in C allow programmers to create, read, write, modify, and delete files. The stdio.h library provides functions to handle file operations.
Types of File Operations
- Creating a File – Using fopen() in write (w) or append (a) mode.
- Opening a File – Using fopen() in various modes (r, w, a, etc.).
- Reading a File – Using fscanf(), fgets(), or fread().
- Writing to a File – Using fprintf(), fputs(), or fwrite().
- Closing a File – Using fclose().
- Deleting a File – Using remove().
- Renaming a File – Using rename().
Opening and Closing a File (Using fopen() and fclose())
The fopen() function is used to open a file in different modes.
Syntax:
FILE *file_pointer; file_pointer = fopen("filename.txt", "mode");
- filename.txt → Name of the file to open.
- “mode” → Specifies how the file is opened.
File Opening Modes:
Mode | Description |
---|---|
“r” | Open for reading (file must exist) |
“w” | Open for writing (creates a new file or overwrites an existing file) |
“a” | Open for appending (creates a new file if it doesn’t exist) |
“r+” | Open for both reading and writing |
“w+” | Open for reading and writing (overwrites existing file) |
“a+” | Open for reading and appending |
Closing a File in C (Using fclose())
The fclose() function is used to close an opened file.
Syntax:
fclose(file_pointer);
It flushes any buffered data and releases resources.
Example: Opening and Closing a File
#include <stdio.h> int main() { // Open file in write mode FILE *file = fopen("sanfoundry_quiz.txt", "w"); if (file == NULL) { printf("Error opening file!\n"); return 1; } // Write to file fprintf(file, "Sanfoundry Certification - File Handling in C\n"); fclose(file); // Close the file printf("File successfully opened, written, and closed.\n"); return 0; }
This C program opens a file named sanfoundry_quiz.txt in write mode. It checks if the file opens successfully. If there’s an error, it displays a message and exits. If successful, it writes “Sanfoundry Certification – File Handling in C” to the file using fprintf(). After writing, the file is closed with fclose(), and a success message is printed.
Writing to a File (Using fprintf() and fputs()) in C
In C, we can write data to a file using fprintf() and fputs() functions.
1. Writing Using fprintf()
The fprintf() function works like printf() but writes formatted data to a file.
Syntax:
fprintf(file_pointer, "format_string", values);
- file_pointer → Pointer to the opened file
- “format_string” → The format specifier like %d, %s, etc.
- values → Data to write in the file
2. Writing Using fputs()
The fputs() function writes a string to a file.
Syntax:
fputs("String to write", file_pointer);
- file_pointer → Pointer to the opened file
- “String to write” → The string that will be written
Example: Writing to a File Using fprintf() and fputs()
#include <stdio.h> int main() { // Open file in write mode FILE *file = fopen("sanfoundry_notes.txt", "w"); if (file == NULL) { printf("Error opening file!\n"); return 1; } // Using fprintf() fprintf(file, "Sanfoundry Certification: C Programming\n"); fputs("Topic: File Handling in C\n", file); // Using fputs() fclose(file); // Close the file printf("Data written successfully to the file.\n"); return 0; }
This C program demonstrates how to write data to a file using both fprintf() and fputs(). The program opens a file named sanfoundry_notes.txt in write mode (“w”). If the file fails to open, it prints an error message and exits. If the file opens successfully, it uses fprintf() to write the string “Sanfoundry Certification: C Programming” and then fputs() to write the string “Topic: File Handling in C” to the file. After writing, the file is closed using fclose(), and a success message is printed to confirm that the data was written successfully.
Reading from a File in C (Using fscanf() and fgets()) in C
In C programming, you can read data from a file using the functions fscanf() (for formatted input) and fgets() (for string input). Both are widely used in file handling.
1. Using fscanf()
Similar to scanf(), but reads formatted data from a file.
Syntax:
fscanf(file_pointer, "format_specifier", &variable);
2. Using fgets()
Reads a line or string from a file, including whitespace, until a newline or EOF.
Syntax:
fgets(string, size, file_pointer);
- string → Array to store the input
- size → Maximum number of characters to read
- file_pointer → Pointer to the file
Example: Reading from a File Using fscanf() and fgets()
#include <stdio.h> int main() { FILE *file = fopen("sanfoundry_data.txt", "r"); // Open in read mode if (file == NULL) { printf("Unable to open file!\n"); return 1; } char name[30]; int score; // Reading using fscanf() fscanf(file, "%s %d", name, &score); printf("Student Name: %s\n", name); printf("Score: %d\n", score); // Move to next line and read using fgets() char line[100]; fgets(line, sizeof(line), file); printf("Extra Line: %s", line); fclose(file); return 0; }
Output (Assume file contains):
Arya 95
This is a Sanfoundry C quiz.
Output:
Student Name: Arya Score: 95 Extra Line: This is a Sanfoundry C quiz.
This C program reads data from “sanfoundry_data.txt” using fscanf() and fgets(). It first opens the file in read mode and checks for errors. Then, it reads a student’s name and score using fscanf() and prints them. Next, it reads an extra line using fgets(). Finally, it closes the file to free resources. This simple program demonstrates basic file reading in C.
Writing and Reading Binary Data (Using fwrite() and fread()) in C
Binary files store data in the same format used in memory, making them efficient for storing structures and arrays.
fwrite() – Writing to a Binary File
Syntax:
fwrite(&data, size, count, file_pointer);
- &data – address of the variable or structure
- size – size of each element
- count – number of elements to write
- file_pointer – pointer to the file
fread() – Reading from a Binary File
Syntax:
fread(&data, size, count, file_pointer);
Works just like fwrite(), but reads binary data into memory.
Example: Using fwrite() and fread() in C
#include <stdio.h> #include <string.h> struct QuizResult { char username[30]; int score; }; int main() { struct QuizResult q1 = {"quiz_master", 92}; struct QuizResult loaded; // Write to binary file FILE *fp = fopen("quizdata.dat", "wb"); if (fp == NULL) { printf("Unable to open file.\n"); return 1; } fwrite(&q1, sizeof(struct QuizResult), 1, fp); fclose(fp); // Read from binary file fp = fopen("quizdata.dat", "rb"); if (fp == NULL) { printf("Unable to open file.\n"); return 1; } fread(&loaded, sizeof(struct QuizResult), 1, fp); fclose(fp); printf("User: %s\n", loaded.username); printf("Score: %d\n", loaded.score); return 0; }
Output:
User: quiz_master Score: 92
This C program saves and loads a quiz result using a binary file. It writes a QuizResult struct to “quizdata.dat” with fwrite(), then reads it back using fread(). It checks for errors and ensures proper file handling. Finally, it prints the stored username and score.
Renaming and Deleting a File in C
- rename(“oldname.txt”, “newname.txt”): Renames a file from old name to new name.
- remove(“filename.txt”): Deletes the file from disk.
Syntax:
int rename(const char *oldname, const char *newname); int remove(const char *filename);
Example:
#include <stdio.h> int main() { FILE *fp; // Create a file named "oldfile.txt" fp = fopen("oldfile.txt", "w"); if (fp == NULL) { printf("Error creating file.\n"); return 1; } fprintf(fp, "Sanfoundry Certification Practice\n"); fclose(fp); // Rename file to "quizfile.txt" if (rename("oldfile.txt", "quizfile.txt") == 0) printf("File renamed successfully.\n"); else printf("Error renaming file.\n"); // Delete the renamed file if (remove("quizfile.txt") == 0) printf("File deleted successfully.\n"); else printf("Error deleting file.\n"); return 0; }
Output:
File renamed successfully.
File deleted successfully.
This C program creates, renames, and deletes a file. It first writes text to “oldfile.txt“, then renames it to “quizfile.txt” using rename(). Finally, it deletes the renamed file with remove(), checking for errors at each step.
File Handling Functions in C
File handling in C allows programs to create, read, write, and manipulate files. The stdio.h library provides various functions to perform these operations.
Function | Purpose |
---|---|
fopen() | Opens a file for reading, writing, or appending |
fclose() | Closes an opened file |
fprintf() | Writes formatted data to a file (similar to printf()) |
fscanf() | Reads formatted data from a file (similar to scanf()) |
fputc() | Writes a single character to a file |
fgetc() | Reads a single character from a file |
fputs() | Writes a string to a file |
fgets() | Reads a string from a file |
fread() | Reads binary data from a file |
fwrite() | Writes binary data to a file |
feof() | Checks if the end of the file is reached |
fseek() | Moves the file pointer to a specific position |
ftell() | Returns the current position of the file pointer |
rewind() | Moves the file pointer to the beginning |
remove() | Deletes a file |
rename() | Renames a file |
File Pointers in C
In C, a file pointer is a special pointer of type FILE * that is used to access files. It is used with standard file handling functions like fopen(), fclose(), fread(), fwrite(), etc. The file pointer keeps track of where we are in the file (i.e., the current read/write position).
Syntax:
FILE *fp;
Here, fp is a pointer to a FILE object, which contains information about the file such as its current position, mode, and more.
Example:
#include <stdio.h> int main() { FILE *fp; // Opening a file for writing fp = fopen("sanfoundry_file.txt", "w"); if (fp == NULL) { printf("File could not be opened.\n"); return 1; } // Writing to file using file pointer fprintf(fp, "This file is for Sanfoundry Quiz Practice.\n"); // Closing file fclose(fp); printf("Data written successfully using file pointer.\n"); return 0; }
Console Output:
Data written successfully using file pointer.
Contents of the File sanfoundry_file.txt:
This file is for Sanfoundry Quiz Practice.
This C program writes text to a file. It opens “sanfoundry_file.txt” in write mode using fopen(). If successful, it writes a line using fprintf(), then closes the file with fclose(). Finally, it confirms the write operation.
Error Handling in File Operations in C
When working with files in C, errors can occur due to various reasons such as:
- File not found (while reading)
- Insufficient permissions
- Disk full or file system issues
- Invalid file mode
To handle these errors properly, we use error checking mechanisms with functions like fopen(), fclose(), fgets(), and fwrite(). Additionally, C provides perror() and strerror() for debugging.
Example 1: Handling fopen() Failure
#include <stdio.h> int main() { FILE *file; // Try to open a non-existent file file = fopen("nonexistent.txt", "r"); if (file == NULL) { perror("Error opening file"); return 1; } fclose(file); return 0; }
Output:
Error opening file: No such file or directory
2. Using ferror() and feof() Example
#include <stdio.h> int main() { FILE *file = fopen("data.txt", "r"); if (file == NULL) { perror("Failed to open file"); return 1; } char ch; while ((ch = fgetc(file)) != EOF) { putchar(ch); } if (ferror(file)) { printf("\nAn error occurred while reading the file.\n"); } else if (feof(file)) { printf("\nReached end of file.\n"); } fclose(file); return 0; }
3. Using strerror() for More Customization
strerror() converts error codes into readable strings.
#include <stdio.h> #include <errno.h> // Required for error handling int main() { FILE *fp = fopen("nonexistent.txt", "r"); if (fp == NULL) { printf("Error: %s\n", strerror(errno)); // Converts error code to string return 1; } fclose(fp); return 0; }
- errno is a global variable that stores the error code.
- strerror(errno) converts it into a human-readable message.
4. Handling Write Errors
Always check the return value of fprintf() and fputs().
#include <stdio.h> int main() { // Trying to write to a restricted file FILE *fp = fopen("/root/protected.txt", "w"); if (fp == NULL) { perror("Error opening file"); return 1; } if (fprintf(fp, "Writing test\n") < 0) { perror("Error writing to file"); } fclose(fp); return 0; }
If there’s a permission issue, it prints:
Error opening file: Permission denied
FAQs on File Handling in C
1. What is file handling in C?
File handling in C allows programs to create, read, write, and modify files. It helps in storing data permanently instead of keeping it in temporary memory.
2. Why is file handling important?
File handling is useful for storing large amounts of data, preserving information between program executions, and sharing data between different applications.
3. What are the basic operations in file handling?
The main operations include creating a file, opening a file, reading from a file, writing to a file, appending data, and closing a file.
4. What is a file pointer in C?
A file pointer is a special pointer that helps manage and access files. It keeps track of the file being used and the current position within the file.
5. What are the different file opening modes?
There are various modes such as read-only, write-only, append mode, and read-write combinations. These modes control how the file is accessed and whether existing data is preserved or overwritten.
6. What happens if you open a file in write mode and it already exists?
The existing contents of the file will be erased. If data loss is a concern, use append mode instead.
7. How can you append data to an existing file?
Appending mode allows adding new content to the end of a file without erasing existing data.
8. What is the difference between read-write mode and write-read mode?
One mode allows modifying an existing file while keeping its data, whereas the other starts fresh and erases any previous content.
9. What are some best practices for file handling in C?
Always check if a file was successfully opened, handle errors properly, close files after use, and use the correct file modes to prevent data loss.
Key Points to Remember
Here is the list of key points we need to remember about “File Handling in C”.
- File handling in C allows programs to create, open, read, write, and close files for persistent data storage.
- Text files store human-readable characters in ASCII format, while binary files store raw data more efficiently.
- Common file operations include creating, opening, reading, writing, closing, renaming, and deleting files.
- The fopen() function opens files in modes like r, w, a, and r+, while fclose() ensures data is saved and resources are released.
- Writing functions include fprintf() for formatted text, fputs() for strings, and fwrite() for binary data.
- Reading functions include fscanf() for formatted input, fgets() for lines of text, and fread() for binary data.
- Functions like fseek(), ftell(), and rewind() help navigate files using file pointers (FILE *fp).
- Error handling includes checking if fopen() returns NULL and using feof() to detect the end of a file.
- Practice Computer Science MCQs
- Watch Advanced C Programming Videos
- Apply for Computer Science Internship
- Check C Books
- Check Computer Science Books