Why files are needed?
Files play a crucial role in programming & data storage. Let’s look at some reasons on why files are needed:
1. Persistence: Files allow data to persist even after a program has finished executing. This means that you can save data to a file & access it later, even if the program has been closed or the computer has been turned off.
2. Data organization: Files provide a structured way to organize and store data. You can have different files for different purposes, such as configuration files, log files, or data files, making it easier to manage and access the data when needed.
3. Data sharing: Files facilitate data sharing between different programs or systems. You can write data to a file in one program and read it from another program, enabling communication and data exchange between them.
4. Large data handling: When dealing with large amounts of data that cannot fit into memory, files become essential. You can store the data in files & read it in smaller chunks as needed, allowing you to process large datasets efficiently.
5. Backup & recovery: Files serve as a backup mechanism. By storing important data in files, you can create backups & recover the data in case of system failures, accidental deletions, or other disasters.
6. Record-keeping: Files are used to keep records of various activities, such as transaction logs, user activity, or system events. This helps in auditing, debugging, & maintaining a history of operations.
Types of Files
In C programming, there are two main types of files:
1. Text files
- Text files contain human-readable characters and are usually created and edited using a text editor.
- They store data in the form of ASCII or Unicode characters.
- Each line in a text file ends with a special character called the newline character ('\n').
- Examples of text files include .txt, .c, .h, and .csv files.
2. Binary files
- Binary files contain data in binary format, which is not directly readable by humans.
- They store data in the form of bytes or machine-readable format.
- Binary files can contain a variety of data types, including numbers, strings, structures, and more.
- Examples of binary files include .bin, .dat, and .exe files.
The main difference between text files and binary files lies in how the data is stored and interpreted. Text files are more portable and can be easily viewed and edited using a text editor, while binary files are more compact and efficient for storing complex data structures.
You're absolutely right! Adding examples will make the explanations clearer and more practical. Let me include examples for each file operation.
File Operations
When we work with files in C, we can perform many fundamental operations. These file operations give you freedom to create, read, write, and manipulate files efficiently. Let's take a look at the essential file operations along with examples:
1. Opening a file
- Before performing any file operations, you need to open the file using the `fopen()` function.
- The `fopen()` function takes two arguments: the filename and the mode in which to open the file.
- The mode specifies how you want to interact with the file, such as read mode ("r"), write mode ("w"), append mode ("a"), or binary mode ("b").
Example:
FILE *file = fopen("example.txt", "r");
2. Closing a file
- After you have finished working with a file, it is important to close it using the `fclose()` function.
- Closing a file releases the resources associated with it and ensures that any pending data is written to the file.
- Failing to close a file can lead to resource leaks and potential data loss.
Example:
fclose(file);
3. Reading from a file
- To read data from a file, you can use functions like `fgetc()`, `fgets()`, `fscanf()`, or `fread()`.
- These functions allow you to read characters, strings, formatted data, or binary data from a file.
- You can read data sequentially or use random access techniques to read from specific positions in the file.
Example (reading a character):
char ch = fgetc(file);
Example (reading a line):
char line[100];
fgets(line, sizeof(line), file);
4. Writing to a file
- To write data to a file, you can use functions like `fputc()`, `fputs()`, `fprintf()`, or `fwrite()`.
- These functions allow you to write characters, strings, formatted data, or binary data to a file.
- You can write data sequentially or use random access techniques to write to specific positions in the file.
Example (writing a character):
fputc('A', file);
Example (writing a string):
fputs("Hello, World!", file);
5. Positioning in a file
- C provides functions like `fseek()`, `ftell()`, and `rewind()` to manipulate the file position indicator.
- These functions allow you to move the file position indicator to a specific location within the file, determine the current position, or reset the position to the beginning of the file.
Example (moving the file position indicator):
fseek(file, 10, SEEK_SET);
Example (getting the current position):
long position = ftell(file);
Working with Files
Now that we have explained the basic file operations, let's understand the details of working with files in C. The steps to work with files are mentioned below:
1. Declare a file pointer
- To work with files, you need to declare a file pointer variable of type `FILE*`.
- The file pointer will be used to reference the file and perform operations on it.
Example:
FILE *file;
2. Open the file
- Use the `fopen()` function to open the file and associate it with the file pointer.
- Specify the filename and the mode in which you want to open the file.
- The `fopen()` function returns a file pointer if the file is successfully opened, or `NULL` if it fails.
Example:
file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
3. Perform file operations
- Once the file is open, you can perform various operations on it, such as reading, writing, or positioning.
- Use the appropriate functions based on your requirements, such as `fgetc()`, `fgets()`, `fscanf()`, `fputc()`, `fputs()`, `fprintf()`, etc.
- Be sure to check the return values of these functions to handle any errors that may occur.
4. Close the file
- After you have finished working with the file, it's important to close it using the `fclose()` function.
- Closing the file ensures that any pending data is written to the file and releases the resources associated with it.
Example:
fclose(file);
Let’s take a look at a complete example that shows opening a file, reading its contents, and closing the file:
#include <stdio.h>
int main() {
FILE *file;
char ch;
file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
while ((ch = fgetc(file)) != EOF) {
printf("%c", ch);
}
fclose(file);
return 0;
}

You can also try this code with Online C Compiler
Run CodeIn this example, we open the file "example.txt" in read mode, read its contents character by character using `fgetc()` until we reach the end of the file (EOF), and then close the file using `fclose()`.
How to Read a File in C?
Reading a file is a basic task in C. There are several methods to read data from a file. Let's take a look at those different ways to read a file in C:
1. Reading a character at a time:
- Use the `fgetc()` function to read a single character from the file.
- This function reads one character at a time and returns the character as an `int` value.
- You can use a loop to read characters until the end of the file is reached.
2. Reading a line at a time:
- Use the `fgets()` function to read a line of text from the file.
- This function reads characters until it encounters a newline character (`\n`) or reaches the specified maximum number of characters.
- The newline character is also read and stored in the buffer.
3. Reading formatted data:
- Use the `fscanf()` function to read formatted data from the file.
- This function reads data according to a specified format string, similar to the `scanf()` function.
- You can specify the format specifiers to read integers, floating-point numbers, strings, or any other data type.
4. Reading binary data:
- Use the `fread()` function to read binary data from the file.
- This function reads a specified number of bytes from the file into a buffer.
- It is commonly used when working with binary files or when reading structured data.
Different Methods to Read a File in C
Now, let's discuss the different methods of reading a file in C in more detail.
Read a File in C Using fgetc()
The `fgetc()` function is used to read a single character from a file. It reads characters one by one and returns the character as an `int` value. When the end of the file is reached, it returns `EOF` (end of file).
For example:
#include <stdio.h>
int main() {
FILE *file;
int ch;
file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
while ((ch = fgetc(file)) != EOF) {
printf("%c", ch);
}
fclose(file);
return 0;
}

You can also try this code with Online C Compiler
Run Code
In this example:
1. We open the file "example.txt" in read mode using `fopen()`.
2. We declare an integer variable `ch` to store the character read by `fgetc()`.
3. We use a `while` loop to read characters from the file until `EOF` is encountered.
- Inside the loop, we call `fgetc(file)` to read a character from the file.
- The character is stored in the `ch` variable.
- We print the character using `printf()`.
4. After the loop ends, we close the file using `fclose()`.
When it is useful: This method is useful when you want to process the file character by character or perform character-level operations.
Read a File in C Using fgets()
The `fgets()` function is used to read a line of text from a file. It reads characters until it encounters a newline character (`\n`) or reaches the specified maximum number of characters. The newline character is also read and stored in the buffer.
For example:
#include <stdio.h>
int main() {
FILE *file;
char line[100];
file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
while (fgets(line, sizeof(line), file) != NULL) {
printf("%s", line);
}
fclose(file);
return 0;
}

You can also try this code with Online C Compiler
Run Code
In this example:
1. We open the file "example.txt" in read mode using `fopen()`.
2. We declare a character array `line` with a size of 100 to store each line read by `fgets()`.
3. We use a `while` loop to read lines from the file until `fgets()` returns `NULL`, indicating the end of the file.
- Inside the loop, we call `fgets(line, sizeof(line), file)` to read a line from the file.
- The line is stored in the `line` array.
- We print the line using `printf()`.
4. After the loop ends, we close the file using `fclose()`.
The `fgets()` function reads up to `sizeof(line) - 1` characters from the file & stores them in the `line` array. It automatically adds a null terminator (`\0`) at the end of the line.
When it is useful: This method is useful when you want to read a file line by line and process each line separately. It is commonly used when working with text files, where each line represents a separate record or entry.
Read a File in C Using fscanf()
The `fscanf()` function is used to read formatted data from a file. It works similarly to the `scanf()` function but reads from a file instead of the standard input. You can specify the format specifiers to read integers, floating-point numbers, strings, or any other data type.
For example:
#include <stdio.h>
int main() {
FILE *file;
int num;
float price;
char name[50];
file = fopen("data.txt", "r");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
while (fscanf(file, "%d %f %s", &num, &price, name) != EOF) {
printf("Number: %d, Price: %.2f, Name: %s\n", num, price, name);
}
fclose(file);
return 0;
}

You can also try this code with Online C Compiler
Run Code
Assume the content of the "data.txt" file is:
1 10.50 Apple
2 5.75 Banana
3 8.20 Orange
In this example:
1. We open the file "data.txt" in read mode using `fopen()`.
2. We declare variables `num`, `price`, and `name` to store the formatted data read by `fscanf()`.
3. We use a `while` loop to read formatted data from the file until `fscanf()` returns `EOF`, indicating the end of the file.
- Inside the loop, we call `fscanf(file, "%d %f %s", &num, &price, name)` to read an integer, a floating-point number, and a string from the file.
- The values are stored in the corresponding variables.
- We print the values using `printf()`.
4. After the loop ends, we close the file using `fclose()`.
The `fscanf()` function reads the formatted data from the file according to the specified format string. In this example, `"%d %f %s"` specifies that we expect an integer, a floating-point number, and a string separated by whitespace.
When it is useful: This method is useful when you have structured data in a file, such as comma-separated values (CSV) or tab-separated values (TSV), and you want to read and process the data according to a specific format.
Read a File in C Using fread()
The `fread()` function reads binary data from a file. It reads a specified number of bytes from the file into a buffer. This method is commonly used when working with binary files or when reading structured data.
For example:
#include <stdio.h>
struct Record {
int id;
char name[50];
};
int main() {
FILE *file;
struct Record record;
file = fopen("records.bin", "rb");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
while (fread(&record, sizeof(struct Record), 1, file) == 1) {
printf("ID: %d, Name: %s\n", record.id, record.name);
}
fclose(file);
return 0;
}

You can also try this code with Online C Compiler
Run Code
In this example:
1. We define a structure `Record` that represents the data we want to read from the file.
2. We open the file "records.bin" in binary read mode using `fopen()` with the mode "rb".
3. We declare a variable `record` of type `struct Record` to store the data read by `fread()`.
4. We use a `while` loop to read records from the file until `fread()` returns a value other than 1.
- Inside the loop, we call `fread(&record, sizeof(struct Record), 1, file)` to read one record from the file.
- The `fread()` function takes four arguments:
- `&record`: A pointer to the buffer where the data will be stored.
- `sizeof(struct Record)`: The size of each record in bytes.
- `1`: The number of records to read.
- `file`: The file pointer.
- The data read from the file is stored in the `record` variable.
- We print the values of the `id` and `name` fields of the `record` using `printf()`.
5. After the loop ends, we close the file using `fclose()`.
The `fread()` function reads a specified number of bytes from the file into the provided buffer. In this example, it reads one record at a time, where each record is of type `struct Record`.
When this is useful: This method is useful when you have binary files or structured data that need to be read in a specific format. It allows you to read the data directly into a structure or buffer, making it efficient for handling large amounts of binary data.
Frequently Asked Questions
What is the difference between text files & binary files in C?
Text files contain human-readable characters, while binary files store data in binary format, which is not directly readable by humans.
How do I choose the appropriate method to read a file in C?
The choice depends on the type of data you want to read. Use `fgetc()` for character-by-character reading, `fgets()` for reading lines, `fscanf()` for formatted data, & `fread()` for binary data.
What should I do if an error occurs while reading a file?
Always check the return value of file handling functions. If an error occurs, you can handle it gracefully by displaying an error message and taking appropriate action, such as closing the file and exiting the program.
Conclusion
In this article, we discussed the basics of reading files in C. We covered different methods, including reading characters with `fgetc()`, reading lines with `fgets()`, reading formatted data with `fscanf()`, and reading binary data with `fread()`.
You can also check out our other blogs on Code360.