File Handling in C
File handling in C allows you to work with files on your computer's storage. It enables reading data from files, writing data to files, and performing other file-related operations. The standard library provides functions and types for file handling in C.
Here are the basic steps involved in file handling in C:
1. File Pointer
- To work with files, you need to declare a file pointer of type FILE.
- The file pointer will hold the address of the file you want to read from or write to.
Syntax
FILE *file_pointer;
Example
FILE *fp;
2. Opening a File
- Before reading from or writing to a file, you need to open it using the fopen() function.
- The fopen() function takes two arguments: the file name (or path) and the mode.
Syntax
file_pointer = fopen(file_name, mode);
Example
fp = fopen("file.txt", "r"); // Opens the file.txt in read mode
Common file modes:
- "r": Read mode
- "w": Write mode (creates a new file or overwrites an existing file)
- "a": Append mode (appends data to an existing file or creates a new file)
- "r+": Read and write mode
3. Reading from a File:
- To read data from a file, you can use functions like fscanf() or fgets().
- fscanf() reads formatted data, while fgets() reads a line of text.
Example using fscanf():
int num;
fscanf(fp, "%d", &num); // Reads an integer from the file
Example using fgets():
char line[100];
fgets(line, sizeof(line), fp); // Reads a line of text from the file
4. Writing to a File:
- To write data to a file, you can use functions like fprintf() or fputs().
- fprintf() writes formatted data, while fputs() writes a string.
Example using fprintf():
int num = 42;
fprintf(fp, "%d\n", num); // Writes the value of num to the file
Example using fputs():
char message[] = "Hello, world!";
fputs(message, fp); // Writes the string to the file
5. Closing a File:
- After you finish working with a file, it is important to close it using the fclose() function.
- Closing the file ensures that all data is written and releases system resources.
Syntax
fclose(file_pointer);
Example
fclose(fp); // Closes the file
File handling in C allows you to perform various operations on files, such as reading data, writing data, modifying file contents, and more. It is essential to handle file-related errors and check if file operations are successful before proceeding. Additionally, you should always close files properly to avoid resource leaks.