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

SEM1-BPL - Lesson13-File Handling

This document covers file handling in the C programming language, detailing concepts such as file I/O, streams, and various I/O functions. It explains the importance of files for data persistence and provides an overview of text and binary streams, along with the functions used for file operations. Key functions like fopen(), fclose(), fread(), fwrite(), and fseek() are discussed, emphasizing their roles in managing file input and output.

Uploaded by

tuan anh nguyen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

SEM1-BPL - Lesson13-File Handling

This document covers file handling in the C programming language, detailing concepts such as file I/O, streams, and various I/O functions. It explains the importance of files for data persistence and provides an overview of text and binary streams, along with the functions used for file operations. Key functions like fopen(), fclose(), fread(), fwrite(), and fseek() are discussed, emphasizing their roles in managing file input and output.

Uploaded by

tuan anh nguyen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

BASIC PROGRAMMING LANGUAGE

LESSON 13

File Handling
CONTENT
1. File I/O Concepts
2. Working with Streams
• Text Stream
• Binary Stream

3. I/O Functions:
• open(), close()
• fread(), fwrite(), fseek()
• fscanf(), fprintf()

4. Summary
Basic Programming Language 2
Why Files Are Needed?
• When a program is terminated, the entire data is lost. Storing in a file will
preserve your data even if the program terminates.
• If you have to enter a large number of data, it will take a lot of time to enter
them all.
However, if you have a file containing all the data, you can easily access
the contents of the file using a few commands in C.
• You can easily move your data from one computer to another without any
changes.

Basic Programming Language 3


File Input / Output
• A file is a container in computer storage devices used for storing data.
• All I/O operations in C are carried out using functions from the standard
library.
• This approach makes the C file system very powerful and flexible.
• I/O in C is unique because data may be transferred in its internal binary
representation or in a human-readable text format.

Basic Programming Language 4


File Input / Output

Basic Programming Language 5


Streams
• The C file system works with a wide variety of devices including printers,
disk drives, tape drives and terminals.
• Though all these devices are very different from each other, the buffered
file system transforms each device into a logical device called a stream.
• Since all streams act similarly, it is easy to handle the different devices.
• There are two types of streams
• Text stream
• Binary stream

Basic Programming Language 6


Streams

Basic Programming Language 7


Text Streams
• A text stream is a sequence of characters that can be organized into
lines terminated by a new line character.
• In a text stream, certain character translations may occur as required by
the environment.
• Therefore, there may not be a one-to-one relationship between the
characters that are written (or read) and those in the external device.
• Also, because of possible translations, the number of characters written
(or read) may not be the same as those in the external device.

Basic Programming Language 8


Binary Streams
• A binary stream is a sequence of bytes with a one-to-one correspondence
to those in the external device, that is, there are no character translations.
• The number of bytes written (or read) is the same as the number on the
external device.
• Binary streams are a flat sequence of bytes, which do not have any flags
to indicate the end of file or end of record.
• The end of file is determined by the size of the file.

Basic Programming Language 9


Files
• A file can refer to anything from a disk file to a terminal or a printer.
• A file is associated with a stream by performing an open operation and
disassociated by a close operation.
• When a program terminates normally, all files are automatically closed.
• When a program crashes, the files remain open.
• File handling in C: Using standard I/O in C using fprintf(), fscanf(), fread(),
fwrite(), fseek().

Basic Programming Language 10


File Functions
Name Function
fopen() Opens a file
fclose() Closes a file
fputc() Writes a character to a file
fgetc() Reads a character from a file
fread() Reads from a file to a buffer
fwrite() Writes from a buffer to a file
fseek() Seeks a specific location in the file
fprintf() Operates like printf(), but on a file
fscanf() Operates like scanf(), but on a file
feof() Returns true if end-of-file is reached

Basic Programming Language 11


File Functions
Name Function
ferror() Returns true if an error has occurred
rewind() Resets the file position locator to the beginning of the file
remove() Erases a file
fflush() Writes data from internal buffers to a specified file

Basic Programming Language 12


File Pointer
• A file pointer is essential for reading or writing files.
• It is a pointer to a structure that contains the file name, current position of
the file, whether the file is being read or written, and whether any errors or
the end of the file have occurred.
• The definitions obtained from <stdio.h> include a structure declaration
called FILE.
• The only declaration needed for a file pointer is:
FILE *fp;

Basic Programming Language 13


Types of Files
• When dealing with files, there are two types of files you should know
about:
• Text files: Text files are the normal .txt files. You can easily create text files
using any simple text editors such as Notepad.
• Binary files: Binary files are mostly the .bin files in your computer. Instead of
storing data in plain text, they store it in the binary form (0's and 1's).

Basic Programming Language 14


File Operations
• In C, you can perform four major operations on files, either text or
binary:
1. Creating a new file
2. Opening an existing file
3. Reading from and writing information to a file
4. Closing a file

Basic Programming Language 15


Working with Text File
• Open File:
• Using fopen() function
• File Manipulation:
• Using fgetc(), fgets() functions read from file
• Using fputc(), fputs() functions write to file

• Close File:
• Using fclose() function

Basic Programming Language 16


Opening a Text File
• The fopen() function opens a stream for use and links a file with that
stream.
• The fopen() function returns a file pointer associated with the file.
• The prototype for fopen() function is:
FILE *fopen(const char *filename, const char *mode);

Basic Programming Language 17


Opening a Text File
Mode Meaning
r Open a text file for reading
w Create a text file for writing
a Append to a text file
r+ Open a text file for read/write
w+ Create a text file for read/write
a+f Append or create a text file for read/write

Basic Programming Language 18


Reading a Text File Example
• Using fgetc() function:

Basic Programming Language 19


Reading a Text File Example
• Using fgets() function:

Basic Programming Language 20


Working with Binary File
• Open File:
• Using fopen() function

• File Manipulation:
• Using fread() functions read from file
• Using fwrite() functions write to file

• Close File:
• Using fclose() function

Basic Programming Language 21


Opening a Binary File
• To open binary file, you also use fopen() function.
• The fopen() function returns a file pointer associated with the file.
• The prototype for fopen() function is:
FILE *fopen(const char *filename, const char *mode);

• Different from opening a text file is adding parameter “b” in opening mode.

Basic Programming Language 22


Opening a Binary File
Mode Meaning
rb Open a binary file for reading
wb Create a binary file for writing
ab Append to a binary file
r+b Open a binary file for read/write
w+b Create a binary file for read/write
a+b Append a binary file for read/write

Basic Programming Language 23


Working with Binary File Example

Basic Programming Language 24


Working with Binary File Example

Basic Programming Language 25


Working with Binary File Example

Basic Programming Language 26


Working with Binary File Example

Basic Programming Language 27


Working with Binary File Example

Basic Programming Language 28


Working with Binary File Example

Basic Programming Language 29


Working with Binary File Example

Basic Programming Language 30


feof() Function
• The function feof() returns true if the end of the file has been reached,
otherwise it returns false (0).
• This function is used while reading binary data.
• The prototype for feof() function is:
int feof(FILE *fp);

Basic Programming Language 31


Erasing File
• The remove() function erases a specified file.
• The remove() function in C can be used to delete a file. The function
returns 0 if files is deleted successfully, other returns a non-zero value.
• The prototype for remove() function is:
int remove (char *fileName);

Basic Programming Language 32


Getting Data Using fseek() Fuctions
• If you have many records inside a file and need to access a record at a
specific position, you need to loop through all the records before it to get
the record. This will waste a lot of memory and operation time.
• An easier way to get to the required data can be achieved using fseek().
• Syntax:
fseek(FILE * stream, long int offset, int whence);
• Example:
// Moves the cursor to the end of the file
fseek(fptr, -sizeof(struct threeNum), SEEK_END);

Basic Programming Language 33


Flushing Streams

• The fflush() function flushes out the buffer depending upon the file type.
• A file opened for read will have its input buffer cleared, while a file opened
for write will have its output buffer written to the files.
• The prototype for fflush() function is:
int fflush(FILE *fp);
• The fflush() function, with a null, flushes all files opened for output.

Basic Programming Language 34


Current Active Pointer
• A pointer is maintained in the FILE structure to keep track of the position
where I/O operations take place.
• Whenever a character is read from or written to the stream, the current
active pointer (known as curp) is advanced.
• The current location of the current active pointer can be found with the
help of the ftell() function.
• The prototype for ftell() function is:
long int ftell(FILE *fp);

Basic Programming Language 35


fprintf() & fscanf() Function
• The buffered I/O system includes fprintf() and fscanf() functions that are
similar to printf() and scanf() except that they operate with files.
• The prototypes of are:
int fprintf(FILE * fp, const char *control_string,..);
int fscanf(FILE *fp, const char *control_string,...);
• The fprintf() and fscanf() though the easiest, are not always the most
efficient.
• Extra overhead is incurred with each call, since the data is written in
formatted ASCII data instead of binary format.
• If speed or file size is a concern, fread() and fwrite() are a better choice.
Basic Programming Language 36
Summary
• All I/O operations in C are carried out using functions from the standard
library.
• I/O in C is unique because data may be transferred in its internal binary
representation or in a human-readable text format.
• The C file system works with a wide variety of devices including printers,
disk drives, tape drives and terminals.
• There are two types of streams - the text and binary streams.
• A file can refer to anything from a disk file to a terminal or a printer.
• A file pointer is essential for reading or writing files.
Basic Programming Language 37
38
38

You might also like