File handling in C
Module 6
Basics of File Handling in C
• File handling in C is the process in which we create, open, read, write,
and close operations on a file. C language provides different functions
such as fopen(), fwrite(), fread(), fseek(), fprintf().
• Types of Files in C
A file can be classified into two types based on the way the file stores
the data. They are as follows:
• Text Files
• Binary Files
• 1. Text Files
• A text file contains data in the form of ASCII characters and is
generally used to store a stream of characters.
• Each line in a text file ends with a new line character (‘\n’).
• It can be read or written by any text editor.
• They are generally stored with .txt file extension.
• Text files can also be used to store the source code.
• Binary Files
• A binary file contains data in binary form (i.e. 0’s and 1’s) instead of
ASCII characters. They contain data that is stored in a similar manner
to how it is stored in the main memory.
• The binary files can be created only from within a program and their
contents can only be read by a program.
• More secure as they are not easily readable.
• They are generally stored with .bin file extension.
C File Operations
• Creating a new file – fopen() with attributes as “a” or “a+” or “w” or
“w+”
• Opening an existing file – fopen()
• Reading from file – fscanf() or fgets()
• Writing to a file – fprintf() or fputs()
• Moving to a specific location in a file – fseek(), rewind()
• Closing a file – fclose()
File Pointer in C
• A file pointer is a reference to a particular position in the opened file.
It is used in file handling to perform all file operations such as read,
write, close.
FILE* pointer_name;
Open a File in C
FILE* fopen(const char *file_name, const char *access_mode);
Parameters
file_name: name of the file when present in the same directory as the source file. Otherwise, full path.
access_mode: Specifies for what operation the file is being opened
Example of Opening a File
• // C Program to illustrate file opening
• #include <stdio.h>
• #include <stdlib.h>
• int main()
• {
• // file pointer variable to store the value returned by
• // fopen
• FILE* fptr;
• // opening the file in read mode
• fptr = fopen("filename.txt", "r");
• // checking if the file is opened successfully
• if (fptr == NULL) {
• printf("The file is not opened. The program will "
• "now exit.");
• exit(0);
• }
• return 0;
• }
Create a File FILE
in *fptr;
C
fptr = fopen("filename.txt", "w");
// C Program to create a file
#include <stdio.h>
#include <stdlib.h>
int main()
{
// file pointer
FILE* fptr;
// creating file using fopen() access mode "w"
fptr = fopen("file.txt", "w");
// checking if the file is created
if (fptr == NULL) {
printf("The file is not opened. The program will "
"exit now");
exit(0);
}
else {
printf("The file is created Successfully.");
}
return 0;
}