0% found this document useful (0 votes)
14 views

File Handling

The document provides an overview of file handling in C, detailing operations such as creating, opening, writing, reading, renaming, and deleting files. It explains the need for file handling to store data permanently beyond the program's execution and distinguishes between text and binary files. Additionally, it covers essential functions like fopen(), fclose(), fwrite(), fread(), and rename(), along with examples for clarity.

Uploaded by

Arpan Narula
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

File Handling

The document provides an overview of file handling in C, detailing operations such as creating, opening, writing, reading, renaming, and deleting files. It explains the need for file handling to store data permanently beyond the program's execution and distinguishes between text and binary files. Additionally, it covers essential functions like fopen(), fclose(), fwrite(), fread(), and rename(), along with examples for clarity.

Uploaded by

Arpan Narula
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

File Handling in C

Course Instructor:
Dr. Suman Kumar Maji

IIT Patna Chapter-7 1 / 46


File Handling in C

File handling in C is the process of handling file operations such as


creating, opening, writing data, reading data, renaming, and deleting
using the C language functions.
With the help of these functions, we can perform file operations to
store and retrieve the data in/from the file in our program.

IIT Patna Chapter-7 2 / 46


Need of File Handling in C

If we perform input and output operations using the C program, the


data exists as long as the program is running, when the program is
terminated, we cannot use that data again.
File handling is required to work with files stored in the external
memory i.e., to store and access the information to/from the
computer’s external memory. You can keep the data permanently
using file handling.

IIT Patna Chapter-7 3 / 46


Types of Files

A file represents a sequence of bytes. There are two types of files:


text files and binary files-

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.

IIT Patna Chapter-7 4 / 46


FILE Pointer (File*)

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.

IIT Patna Chapter-7 5 / 46


Declaring a File Pointer (FILE*)

Below is the syntax to declare a file pointer-

FILE* file pointer;

IIT Patna Chapter-7 6 / 46


Opening (Creating) a File

A file must be opened to perform any operation.


The fopen() function is used to create a new file or open an existing
file.
You need to specify the mode in which you want to open.
There are various file opening modes explained below, any one of
them can be used during creating/opening a file.
The fopen() function returns a FILE pointer which will be used for
other operations such as reading, writing, and closing the files.
Syntax: Below is the syntax to open a file-

FILE *fopen(const char *filename, const char *mode);

Here, filename is the name of the file to be opened, and mode defines the
file’s opening mode.

IIT Patna Chapter-7 7 / 46


File Opening Modes

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:

"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"

IIT Patna Chapter-7 8 / 46


The following are the different file opening modes-

IIT Patna Chapter-7 9 / 46


Example of Creating a File
In the following example, we are creating a new file. The file mode to
create a new file will be ”w” (write-mode).

IIT Patna Chapter-7 10 / 46


Output:

File created

IIT Patna Chapter-7 11 / 46


Example of Opening a File
In the following example, we are opening an existing file. The file mode
to open an existing file will be ”r” (read-only). You may also use other
file opening mode options explained above.
Note: There must be a file to be opened.

IIT Patna Chapter-7 12 / 46


Output:

File opened.

IIT Patna Chapter-7 13 / 46


Closing a File

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-

int fclose(FILE *fp);

The fclose() function returns zero on success, or EOF if there is an error


in closing the file.
The fclose() function actually flushes any data still pending in the buffer
to the file, closes the file, and releases any memory used for the file.
The EOF is a constant defined in the header file stdio.h.

IIT Patna Chapter-7 14 / 46


Example of Closing a File
In the following example, we are closing an opened file

IIT Patna Chapter-7 15 / 46


Output:

IIT Patna Chapter-7 16 / 46


Writing to a Text File

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.

IIT Patna Chapter-7 17 / 46


Writing Single Character to a File

The fputc() function is an unformatted function that writes a single


character value of the argument ”c” to the output stream referenced by
”fp”.
int fputs(const char *s, FILE *fp);

IIT Patna Chapter-7 18 / 46


Example
In the following code, one character from a given char array is written
into a file opened in the ”w” mode:

IIT Patna Chapter-7 19 / 46


Output:

IIT Patna Chapter-7 20 / 46


Writing String 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);

IIT Patna Chapter-7 21 / 46


Example

The following program writes strings from the given two-dimensional char
array to a file-

IIT Patna Chapter-7 22 / 46


Output

IIT Patna Chapter-7 23 / 46


Writing Formatted String to a File

The fprintf() function sends a formatted stream of data to the disk file
represented by the FILE pointer.

int fprintf(FILE *stream, const char *format [, argument, ...])

IIT Patna Chapter-7 24 / 46


Example

In the following program, we have an array of struct type called


”employee”. The structure has a string, an integer, and a float element.
Using the fprintf() function, the data is written to a file.

IIT Patna Chapter-7 25 / 46


code

IIT Patna Chapter-7 26 / 46


Output:

IIT Patna Chapter-7 27 / 46


Reading from a Text File

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.

IIT Patna Chapter-7 28 / 46


Reading Single Character 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.

int fgetc(FILE * fp);

IIT Patna Chapter-7 29 / 46


Example
The following example reads the given file in a character by character
manner till it reaches the end of file.

IIT Patna Chapter-7 30 / 46


Output:

IIT Patna Chapter-7 31 / 46


Reading String from a File

The fgets() function reads up to ”n 1” characters from the input stream


referenced by ”fp”. It copies the read string into the buffer ”buf”,
appending a null character to terminate the string.
Example:

IIT Patna Chapter-7 32 / 46


Output

IIT Patna Chapter-7 33 / 46


Reading Formatted String from a File
The fscanf() function in C programming language is used to read
formatted input from a file.
int fscanf(FILE *stream, const char *format, ...)
Example

IIT Patna Chapter-7 34 / 46


Output

IIT Patna Chapter-7 35 / 46


File Handing Binary Read and Write Functions

The read/write operations are done in a binary form in the case of a


binary file. You need to include the character ”b” in the access mode
(”wb” for writing a binary file, ”rb” for reading a binary file).
There are two functions that can be used for binary input and output: the
fread() function and the fwrite() function. Both of these functions should
be used to read or write blocks of memories, usually arrays or structures.

IIT Patna Chapter-7 36 / 46


Writing to Binary File

The fwrite() function writes a specified chunk of bytes from a buffer to a


file opened in binary write mode. Here is the prototype to use this
function:

fwrite(*buffer, size, no, FILE);

IIT Patna Chapter-7 37 / 46


Example

IIT Patna Chapter-7 38 / 46


Output

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.

IIT Patna Chapter-7 39 / 46


Reading from Binary File

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:

fread(*buffer, size, no, FILE);

IIT Patna Chapter-7 40 / 46


Example

In the following program, an array of a struct type called ”employee” has


been declared. We use the fread() function to read one block of byte,
equivalent to the size of one employee data, in a file that is opened in
”rb” mode.

IIT Patna Chapter-7 41 / 46


code

IIT Patna Chapter-7 42 / 46


Output

IIT Patna Chapter-7 43 / 46


Renaming a File

The rename() function is used to rename an existing file from an old file
name to a new file name.
Syntax

int rename(const char *old filename, const char *new filename)

IIT Patna Chapter-7 44 / 46


Example

IIT Patna Chapter-7 45 / 46


Output:

IIT Patna Chapter-7 46 / 46

You might also like