File Handling
File Handling
Course Instructor:
Dr. Suman Kumar Maji
Note
Text file- 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”), and generally has a ”.txt” extension.
Binary file- A binary file contains data in raw bits (0 and 1). Different
application programs have different ways to represent bits and bytes and
use different file formats. The image files (.png, .jpg), the executable files
(.exe, .com), etc. are the examples of binary files.
While working with file handling, you need a file pointer to store the
reference of the FILE structure returned by the fopen() function.
The file pointer is required for all file-handling operations.
The fopen() function returns a pointer of the FILE type.
FILE is a predefined struct type in stdio.h and contains attributes
such as the file descriptor, size, and position, etc.
Here, filename is the name of the file to be opened, and mode defines the
file’s opening mode.
The file access modes by default open the file in the text or ASCII
mode.
If you are going to handle binary files, then you will use the following
access modes instead of the above-mentioned ones:
File created
File opened.
Each file must be closed after performing operations on it. The fclose()
function closes an opened file.
Syntax: Below is the syntax of fclose() function-
The following library functions are provided to write data in a file opened
in writeable mode
fputc() : Writes a single character to a file.
fputs(): Writes a string to a file.
fprintf(): Writes a formatted string (data) to a file.
The fputs() function writes the string ”s” to the output stream
referenced by ”fp”.
It returns a non-negative value on success, else EOF is returned in case of
any error.
int fputs(const char *s, FILE *fp);
The following program writes strings from the given two-dimensional char
array to a file-
The fprintf() function sends a formatted stream of data to the disk file
represented by the FILE pointer.
The following library functions are provided to read data from a file that
is opened in read mode-
fgetc(): Reads a single character from a file.
fgets(): Reads a string from a file.
fscanf(): Reads a formatted string from a file.
The fgetc() function reads a character from the input file referenced by
”fp”. The return value is the character read, or in case of any error, it
returns EOF.
When the above program is run, the given file will be created in the
current folder. It will not show the actual data, because the file is in
binary mode.
The fread() function reads a specified chunk of bytes from a file opened
in binary read mode to a buffer of the specified size. Here is the
prototype to use this function:
The rename() function is used to rename an existing file from an old file
name to a new file name.
Syntax