0% found this document useful (0 votes)
20 views36 pages

Unit VI-Part1

Uploaded by

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

Unit VI-Part1

Uploaded by

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

Programming

for Problem
Solving
(CST151)
UNIT-6: File handling

1
Syllabus

UNIT-VI: File handling Streams in C, Types of Files, File


Input/ Output Operations: Modes of file opening, Reading
and writing the file, Closing the files, using fflush()
 A collection of data or
information that are stored on a
computer known as file
 A file is a collection of bytes
stored on a secondary storage device.
 There are four different types of file
 Data files
 Text files
 Program files
 Directory files
 Different types of file store different types
of information
Files
Programs and data are stored on disk in structures called files
Examples
Turbo C++ - binary file
Word 4.0 - binary file
lab1.c - text file
lab1.data - text file
term-paper - text file
 A file has a beginning and an
end. the
 position
We of the
need a file current (in
from tothe beginning
marker
terms
mark of bytes) while reading and write
operation, takes place on a file.
 Initially the marker is at the beginning of the
file. We can move the marker to any other
position in the file.
 The new current position can be specified as
an offset from the beginning the file.
STREAMS IN C
In C, the standard streams are termed as pre-connected input and output
channels between a text terminal and the program (when it begins
execution). Therefore, stream is a logical interface to the devices that are
connected to the computer.

Stream is widely used as a logical interface to a file where a file can refer
to a disk file, the computer screen, keyboard, etc. Although files may differ
in the form and capabilities, all streams are the same.

The three standard streams in C languages are- standard input (stdin),


standard output (stdout) and standard error (stderr).
STREAMS IN C
Standard input (stdin): Standard input is the stream from which the
program receives its data. The program requests transfer of data using
the read operation. However, not all programs require input.

Generally, unless redirected, input for a program is expected from the


keyboard.

Standard output (stdout): Standard output is the stream where a


program writes its output data. The program requests data transfer
using the write operation. However, not all programs generate output.
Buffer Associated
with File Stream
File Terms
Buffer - a temporary storage area used to transfer data back
and forth between memory and auxiliary storage devices
Stream - files are manipulated in C with streams, a stream is a
mechanism that is connected to a file that allows you to access
one element at a time
 A text file can be a stream of characters that
a computer can process sequentially.
 It is processed only in forward direction.
 It is opened for one kind of operation
(reading, writing, or appending) at any give
time.
 We can read only one character at a time
from a text file.
 A binary file is a file consisting of
collection of bytes.
 A binary file is also referred to as a
character stream
Using Files in C
To use files in C, we must follow the steps given below.
Declare a file pointer variable

Open the file

Process the file

Close the file


Manipulating User Files

Step 1: open a stream connected to the file


◦ fopen command

Step 2: read data from the file or write data to the file using the stream
◦ input/output commands

Step 3: close the connection to the file


◦ fclose command
Declare a file pointer variable
There can be a number of files on the disk. In order to access a particular file,
you must specify the name of the file that has to be used. This is accomplished
by using a file pointer variable that points to a structure FILE (defined in
stdio.h). The file pointer will then be used in all subsequent operations in the
file. The syntax for declaring a file pointer is

FILE *file_pointer_name;

For example, if we write

FILE *fp;

Then, fp is declared as a file pointer.

An error will be generated if you use the filename to access a file rather than
the file pointer.
Opening a File
A file must be first opened before data can be read from it or written to it.
In order to open a file and associate it with a stream, the fopen() function is
used. The prototype of fopen() can be given as:
FILE *fopen(const char *file_name, const char *mode);
Using the above prototype, the file whose pathname is the string pointed to
by file_name is opened in the mode specified using the mode. If successful,
fopen() returns a pointer-to-structure and if it fails, it returns NULL.
Mode Meaning

r  Open a text file for reading only. If the file doesn’t exist, it returns

null. w  Opens a file for writing only.


 If file exists, than all the contents of that file are destroyed and new fresh blank
file is copied on the disk and memory with same name
 If file dosen’t exists, a new blank file is created and opened for writing.
 Returns NULL if it is unable to open the file
a  Appends to the existing text
 file Adds data at the end of
 the file.
 If file doesn’t exists then a new file is
created. Returns NULL if it is unable to
open the file.
rb  Open a binary file for reading
wb  Open a binary file for reading

ab  Append to a binary file


Mod Meanin
e
a g
 Append or create a text file for
+
r+ read/write
 Open a binary file for
b
w+ read/write
 Create a binary file for
b
a+ read/write
 Append a binary file for read/write
b
FILE *fp;
fp = fopen("Student.DAT", "r");
if(fp==NULL)
{
printf("\n The file could not be opened");
exit(1);
}
Closing a file
To close an open file, the fclose() function is used which disconnects a file pointer from a file.
After the fclose() has disconnected the file pointer from the file, the pointer can be used to
access a different file or the same file but in a different mode.

The fclose() function not only closes the file but also flushed all the buffers that are
maintained for that file.

If you do not close a file after using it, the system closes it automatically when the program
exits. However, since there is a limit on the number of files which can be open
simultaneously; the programmer must close a file when it has been used. The prototype of
the fclose() function can be given as,

int fclose(FILE *fp);

Here, fp is a file pointer which points to the file that has to be closed. The function returns an
integer value which indicates whether the fclose() was successful or not. A zero is returned if
the function was successful; and a non-zero value is returned if an error occurred.
Read and Write Data from Files
C provides the following set of functions to read data from a file.
fscanf()
fgets()
fgetc()
fread()

C provides the following set of functions to write data to a file.


 fprintf()
 fputs()
 fputc()
 fwrite()
fscanf()
The fscanf() is used to read formatted data from the stream. The syntax
of the

fscanf() can be given as,

int fscanf(FILE *stream, const char *format,…);

The fscanf() is used to read data from the stream and store them
according to the parameter format into the locations pointed by the
additional arguments.
Example: Read the
contents of a file using
fscanf()
 To read contents from an existing file, we
need to open that file in read mode that
means “r” mode
 Algorithm to read data from a file:
1. Open the f i l e i n read mode
2. Read data from the f i l e
3. Wri t e th e data in to an outp u t
4. dev i c ea t
Repe s t eps 3 and 4 un ti l l t he
end of f i l e occurs
5. Stop procedure
fgets()
fgets() stands for file get string. The fgets() function is used to get a string
from a stream. The syntax of fgets() can be given as:
char *fgets(char *str, int size, FILE *stream);

The fgets() function reads at most one less than the number of characters
specified by size (gets size - 1 characters) from the given stream and stores
them in the string str. The fgets() terminates as soon as it encounters either
a newline character or end-of-file or any other error. However, if a newline
character is encountered it is retained. When all the characters are read
without any error, a '\0' character is appended to end the string.
Example: Read the
contents of a file using
fgets()
fgetc()
The fgetc() function returns the next character from stream, or EOF if the end
of file is reached or if there is an error. The syntax of fgetc() can be given as
int fgetc( FILE *stream );

fgetc returns the character read as an int or return EOF to indicate an error or
end of file.
fgetc() reads a single character from the current position of a file (file
associated with stream). After reading the character, the function increments
the associated file pointer (if defined) to point to the next character. However,
if the stream has already reached the end of file, the end-of-file indicator for
the stream is set.
 Generally, a file contains a large amount of
data.
 In a large file, it is difficult to detect the end
of file while reading.
 Inorder to mark the end of a text file,
a special character EOF is stored at the
end.
Read a file character by character and simultaneously display on screen

#include<stdio.h>
void main()
{
FI LE

* f p;
char
ch ;
f p = f o p e n ( “ c l e a r. c ” , ” r ” ) ;
if(fp==NULL)
pr int( “ Unable

to

open

c l e a r. c ” ) ;
else
fread()
The fread() function is used to read data from a file. Its syntax can be given as

int fread( void *str, size_t size, size_t num, FILE *stream );

The function fread() reads num number of objects (where each object is size
bytes) and places them into the array pointed to by str. The data is read from
the given input stream.

Upon successful completion, fread() returns the number of bytes successfully


read. The number of objects will be less than num if a read error or end-of-file
is encountered. If size or num is 0, fread() will return 0 and the contents of str
and the state of the stream remain unchanged. In case of error, the error
indicator for the stream will be set.
The fread() function advances the file position indicator for the stream by the
number of bytes read.
FILE *fp;
char str[11];
fp = fopen("Letter.TXT", "r+");
if(fp==NULL)
{ printf("\n The file could not be opened");
exit(1);
}
fread(str, 1, 10, fp);
str[10]= '\0';
printf("\n First 9 characters of the file are : %s", str);
fclose(fp);
Write a program to count
TASK the number of characters
and number of lines in a
file.

NOTE: Prior to this there is just


include and void main** not
visible in screen shot
TASK Write a program to compare
two files by reading them
and comment if they are
identical or not.

You might also like