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

Binary Files 1

Uploaded by

Bahubali C
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Binary Files 1

Uploaded by

Bahubali C
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 39

Binary Files

 As the volume of input data increases we find


it necessary to store the data permanently on
the disk and read from it.
 The concept of storing data in disks was
introduced. Here, the data can be stored on
disks, the data can be accessed as and when
required and any number of times without
destroying the data.
 The data is stored in the form of file.
 File: file is a collection of related data stored
in auxiliary devices such as CDS, disks etc.
EOF
Pictorial Representation of Data
0100 0001 1001 1101 1111 0110 1001 1010 1011
Types of Files:
1. Text Files.
2. Binary Files.
A text file is the one where data is stored as the stream
of characters than can be processed sequentially.
 Text files are in human readable form.
 Text files can be created and read using any text editors.

A binary file is the one where data is stored on the disk


in the same way as it is represented in the computer
memory.
 Not in human readable form.
 Can be created and read only by specific programs.

Assignment: List out the differences between text and


binary files?
Using a File
A stream associated with a disk file must be
opened using the fopen() library function before
it can be used
It must be closed after use through the fclose()
function.
A disk file stream can be opened either in text
or in binary mode.
After a disk file has been opened, data can be
read from the file, written into the file, or
both.

Stream I/O model specify whether you have to read


from the file, write to the file, or both.
File can be opened either in text or in binary mode.
◦ The stream is a common, logical interface to
the various devices that comprise the
computer.

◦ Stream I/O uses some temporary storage area,


called buffer, for reading from or writing data
to a file.
◦ When a stream linked to a disk file is created, a
buffer is automatically created and associated
with the stream.

◦ A stream is linked to a file while using an open


operation.

◦ There are two types of streams: text and binary.


Four steps used during the manipulation
of binary files:
1. Declare a file pointer variable.
2. Open a file using the fopen()
function.
3. Read/Write the data from/to the
file(Processing the file).
4. Close the file using the fclose()
function.
1. Declaration of File Pointer
 Thisis accomplished by using a variable called a file
pointer, a pointer variable that points to a structure
FILE.
◦ FILE is a structure declared in stdio.h .
◦ For each file that is to be opened, a
pointer to type FILE must be declared.
◦ When the function fopen() is called, that
function creates an instance of the FILE
structure and returns a pointer to that
structure.
◦ This pointer is used in all subsequent
operations on the file.
◦ The syntax for declaring file pointers is as
follows.
◦ FILE *file_pointer_name,…;
◦ For example: FILE *ifp; FILE *ofp;
Declaring a file pointer: Either local/global
FILE *fp; /*fp is a pointer to a structure
file */
fp can be used to open a file, update a file
and to close a file.

Example- Updating a student file in the


college office involves
- Open a file
- Update
- Close a file
Opening a File
To open a file and associate it with a stream,
the fopen() function is used. Its prototype is as
follows.

FILE *fopen(const char *fname, const char


*mode);
EX: FILE *fp;
fp = fopen(“data.txt”, “r”);
File Modes—What Sort of Open
r (read mode):
 -Used for opening an existing file to perform read
operation.
 Used only for text file.
 If file does not exists, an error is returned.
 The contents of file are not lost.
 The file pointer points at the beginning.

w (write mode):
 Used to create a file.
 Used only for text file.
 If the file does not exists, a file is created.
 If file already exists, original contents of file are
lost.
 File pointer points at the beginning.
a (append mode):
 Used to insert data at the end of existing file.
 Used only for text file.
 If file does not exists, a file is created.
 If already exists, file pointer points to the end.
 The new data is inserted at the end.
 Existing data cannot be modified.

 NOTE: If + is suffixed for r,w and a modes, the


file is opened for read/write operation with
same features specified above.
rb (read mode):
 Used for opening an existing file for read
operation.
 Used only for binary file.
 If file does not exists, an error is returned.
 The contents of file are not lost.
 File pointer points at the beginning.

wb (write mode):
 Used to create a file.
 Used only for binary file.
 If the file does not exists, a file is created.
 If file already exists, original contents of file are
lost.
 File pointer points at the beginning.
ab (append mode):
 Used to insert data at the end of existing file.
 Used only for binary file.
 If file does not exists, a file is created.
 If already exists, file pointer points to the end.
 The new data is inserted at the end.
 Existing data cannot be modified.

 NOTE: If + is suffixed for rb,wb and ab modes,


then the file is opened for read/write
operation with same features specified above.
File Handling Functions for Text
File:

Character related functions. Ex: getc() , putc()


Text file
Handling
functions
String related functions. Ex: fscanf() , fprintf()
getc()
 getc() is defined in stdio.h that gets one character
from the file pointer specified.
 Syntax: int getc(FILE *fp);
 On success,the function returns character pointed by
fp.
 The fp will automatically points to next character in
input stream.
 If there is any error, EOF is returned.
putc()
 Outputs a character to a file stream specified using
the pointer.
 Syntax: int putc(int ch, FILE *fp);
 On success, writes a character stored in ch to stream
pointed by fp.
 If there is any error, EOF is returned.
fscanf() :
 Instead of getting input from the keyboard, gets the
input from the specified file.
 As input is read from the file, extra parameter file
pointer has to be passed.
 Other functionality remains as same of scanf().
 Syntax: fscanf(fp, “control string”, list);
ex: fscanf(fp, ”%d %s %f”, &id, name,
salary);
fprintf() :
 Similar to printf() but, instead of displaying the result
on the screen, the result is sent to the file.
 Since the file is used, extra parameter file pointer has
to be passed as parameter.
 Syntax: fprintf(fp, “format”, list);
 ex: fprintf(fp, “%d %s %f)”, id, name, salary);
Standard Library Functions for
Files:
File Open and Close functions: fopen() ,
fclose()
Syntax:

On success: return fp
On failure : returnNULL

Checking the Result of Fopen()


 When the file cannot be opened due to reasons described below,
fopen() will return NULL.

 The reasons include the following:


◦ Use of an invalid filename

◦ Attempt to open a file in a non-existent directory or on a non-


existent disk drive
◦ Attempt to open a non-existent file in mode r
One may check to see whether fopen()
succeeds or fails by writing the following
set of statements.
Closing and Flushing Files

 Thefile is closed using the fclose()function. Its


prototype is
◦ int fclose(FILE *fp);
◦ fclose() returns 0 on success or -1 on error.
◦ When a program terminates (either by reaching the
end of main()
◦ Or by executing the exit() function), all streams
are automatically flushed and closed.
◦ When a file is closed, the file’s buffer is flushed .
◦ The operating system closes all open files before
returning to the operating system.
Block read and write functions: fread() ,
fwrite():
fread():
 Used to read a block of data from a given file.

 When fread() is executed, the function read n no. of items,


each of length size bytes.
 The data read from the file is copied into the memory location
pointed to by ptr.
 It returns no. of items successfully read.
 If no items have been read or when error has occurred or end
of file is reached, the function returns 0(zero).
fwrite() :
 Used to write a block of data into a given file.
 Syntax: int fwrite(void *ptr, int size, int
n,FILE *fp);
where, fp is a file pointer of opened file
where data has to be stored.
ptr: The address of first byte is stored in
ptr.
n : no. of items to be written into the file.
size : length of each item in bytes.
 When fwrite() is executed, it reads n no. of
items each of length size bytes (n*size) from
buffer pointed by the ptr and writes into the
file associated with fp.
 It returns no. of items successfully written.
 If no. of items is less than n, then error occurs.
File status functions:
1.feof( ) 2. ferror( ) 3. clearerr( )

feof() Function
 Detecting the End of a File Using the feof()
Function :
◦ To detect end-of-file, there is library function feof(),
which can be used for both binary- and text-mode files.
◦ int feof(FILE *fp);
◦ The argument fp is the FILE pointer returned by
fopen() when the file was opened.
◦ The function feof() returns 0 if the end-of-file has not
been reached, or a non-zero value if end-of-file has
been reached.
ferror( ) :
 Used to detect an erroroccured during
read/write operation on a file.
 Syntax: int ferror(FILE *fp);
 Return true (non-zero value) if error is detected.
 Returns false(zero value) if an error is not
detected.

clearerr( ) :
 Once an error occurs, the subsequent calls to
ferror() returns true until the error status is
cleared.
 So, to clear the error statusclearerr( ) is used.
 Syntax: void clearer(FILE *fp);
File positioning functions:
 File positioning functions are required in the
following scenarios:
1. For accessing the random data from file.
2. For changing the state of the file ( from read to
write / from write to read).
 Types of file positioning functions:
◦ 1. rewind( )
◦ 2. ftell( )
◦ 3. fseek( )
rewind( ) : When the data is written into the
file, file has to be opened in write mode, then
data will be written and hence the fp points to
the end of the file. But, when data it to be
read from the file,we have to start reading
from beginning.
- In such situations, we may have to close and
open the file again so that fp ponts to the
beginnig. Instead we can use rewind( ) as it
sets the fp to the beginning without closing
the file.
- Used to set the fp to the beginning of the file.

ftell ( ) : Current location.


- It gives the current position of the fp.
- It always gives the no. of byts fp is present
from the beginning of the file relative to zero.
fseek( ) :
- Used to set the fp at the specified position.
- The fp can be moved backward of forward any
number of bytes.
- Syntax: fseek(fp, offset, start_point);
where, fp file pointer
offsetno. of bytes to be moved from start
point.( +ve/-ve)
start_point can take any one value from
below shown.
The function fseek() returns 0 if the indicator is moved
successfully or non-zero in case of an error.
System File Operation:
 There are three:
1. remove a file.
2. rename a file.
3. create a temporary file.
Remove a fie – remove( ) :
- Used to delete /remove a file.
- Syntax: int remove( char *filename);
- This function returns value 0 on success and non-
zero value on failure.
Rename a file - rename( ) :
- Used to rename a file.
- Syntax: int rename (char *old_filename, char
*new_filename);
- This function returns 0 on success and non-zero
value on failure.
Create a temporary file- tmpfile( ) :
- Used to create a temporary binary file in “wb+”
(read/write)mode.
- It is automatically deleted when the program is
terminated.
- Syntax: FILE *tmpfile( );

- This function returns Pointer to a file of type FILE


on success
- It returns NULL on failure.
WORKING WITH TEXT FILES
• C provides four functions that can be used to read
text files from the disk. These are
– fscanf()
– fgets()
– fgetc()
– fread()

• C provides four functions that can be used to write


text files into the disk. These are
– fprintf()
– fputs()
– fputc()
– fwrite()
WORKING WITH BINARY FILES
• The steps for copying a binary file into another
are as follows:
1. Open the source file for reading in binary
mode.
2. Open the destination file for writing in
binary mode.
3. Read a character from the source file.
Remember, when a file is first opened, the
pointer is at the start of the file, so there is
no need to position the file pointer explicitly.
4. If the function feof() indicates that the end
of the source file has been reached, then
close both files and return to the calling
program.
5. If end-of-file has not been reached, write
Sequential Versus Random File Access
Every open file has an associated file position
indicator, which describes where read and
write operations take place in the file.
The position is always specified in bytes
from the beginning of the file.
When a new file is opened, the position
indicator is always at the beginning of the
file, i.e., at position 0.

There are two type of file accessing method :


sequential and random.

Every open file has an associated file position


indicator. The position is always specified in
bytes from the beginning of the file.
RANDOM ACCESS TO FILES OF RECORDS
How to jump to a given position (byte
number) in a file without reading all the
previous data?
For random access to files of records, the following
functions are used.
fseek()
ftell()
rewind()
By using fseek(), one can set the position indicator
anywhere in the file.
The function prototype in stdio.h is
int fseek(FILE *fp, long offset, int origin);
offset: number of locations to move from position
ftell(fp) returns current byte position in file
rewind(fp) resets position to start of file
Cont.
It is the number of bytes to move the file pointer.
This is obtained from the formula:
the desired record number × the size
of one record.
The argument origin specifies the position
indicator’s relative starting point.
By using fseek(), one can set the
position indicator anywhere in
the file.

The function fseek() returns 0 if


the indicator is moved
successfully or non-zero in case
of an error.

To determine the value of a file’s


Deleting a File
The library function remove() is used to delete a file.
Its prototype in stdio.h is
int remove(const char *filename);

The copy and delete operations are also associated


with file management.

In case of remove() function the only precondition is


that the specified file must not be open.

The only restriction in rename() function is that both


names must refer to the same disk drive; a file cannot
be renamed on a different disk drive.
Renaming a File
The rename() function changes the name of an existing
disk file.

The function prototype in stdio.h is as follows:


int rename(const char *oldname, const char
*newname);

Errors can be caused by the following conditions.


The file oldname does not exist.
A file with the name newname already exists.
One tries to rename on another disk.

You might also like