Unit V File Processing: Text Files
Unit V File Processing: Text Files
File
A file is a named collection of related information that is recorded on
secondary storage such as magnetic disks, magnetic tapes and optical disks.
In general, a file is a sequence of bits, bytes, lines or records whose meaning
is defined by the files creator and user.
Types of Files
There are 2 kinds of files in which data can be stored in 2 ways either in
characters coded in their ASCII character set or in binary format. They are
Text Files- Ex: Notepad,Word..
Binary Files- Ex pdf, jpeg,mp3..
Text Files
A Text file contains only the text information like alphabets ,digits and
special symbols. The ASCII code of these characters are stored in these files.
Binary Files
A binary file is a file that uses all 8 bits of a byte for storing the
information .It is the form which can be interpreted and understood by the
computer.
The only difference between the text file and binary file is the data contain
in text file can be recognized by the word processor while binary file data
can’t be recognized by a word processor.
Modes of Operation
File Access Mechanisms
File access mechanism refers to the manner in which the records of a file
may be accessed.There are several ways to access files:
Linear/Sequential access
Direct/Random access
Indexed sequential access
Sequential access
A sequential access is that in which the records are accessed in some
sequence, i.e., the information in the file is processed in order, one record
after the other. This access method is the most primitive one. Example:
Compilers usually access files in this fashion.
Direct/Random access
Random access file organization provides, accessing the records directly.
Each record has its own address on the file with by the help of which it can
be directly accessed for reading or writing.
The records need not be in any sequence within the file and they need not be
in adjacent locations on the storage medium.
Indexed sequential access
This mechanism is built up on base of sequential access.
An index is created for each file which contains pointers to various blocks.
Index is searched sequentially and its pointer is used to access the file
directly.
Streams
A Stream refers to the characters read or written to a program. The streams
are designed to allow the user to access the files efficiently .A stream is a
file or physical device like keyboard, printer and monitor.
The FILE object contains all information about stream like current position,
pointer to any buffer, error and EOF(end of file).
C supports a number of functions that have the ability to perform the basic
file operations which includes :
naming a file
opening a file
reading data from a file
writing data into a file
closing a file
I/O Operations
Once a file is opened, reading out of or writing to it is accomplished using
the standard I/O routines.
fopen() : It creates a new file for use or opens an existing file for use.
fclose() : It closes a file which has been opened for use.
getw() : This function returns the integer value from a given file and
increment the file pointer position to the next message.
Syntax: getw (fptr);
Where fptr is a file pointer which takes the integer value from file.
putw() : This function is used for writing an integer value to a given file.
Syntax: putw (value,fptr);
Where fptr is a file pointer Value is an integer value which is written to a
given file.
OUTPUT:
Enter the integer data
10
20
34
45
0
Reading data from file
10
20
34
45
0
fgetc ()
This function is same as the getc () function. It also reads a single character
from a given file and increment the filepointer.It returns EOF,if the end of
the file is reached or it encounters an error.
Syntax: fgetc (fptr);
ch=fgetc (fptr);
Where fptr is a file pointer.
ch is a variable which receive the character returned by fgetc ().
fputc()
This function writes the character to the specified stream at the current file
position and then increments the file position indicator.
Syntax: fputc(ch,fptr);
Where fptr is a file pointer
ch is a variable written to the file which is pointed by file pointer.
OUTPUT:
Enter data into file
Hai hello how r u I am fine
Reading data from a file
Hai hello how r u I am fine
fgets()
This function is used to read a string from a given file and copies the string
to a memory location which is referenced by an array.
Syntax: fgets(sptr,max,fptr);
Where sptr is a string pointer, which points to an array.
max is the length of the array.
fptr is a file pointer ,which points to a given file.
This function read max-1 characters and places them into array which is
pointed by sptr.This function read character until either a newline or an end
of the file or size of the array occurs. It appends a null character (‘\0’) at the
end of the string. It returns a null pointer if either an end of file or an error
encountered.
fputs()
This function is used to write a string to a given file.
Syntax: fputs (sptr, fptr);
Where sptr is a pointer which points to an array
fptr is a file pointer which is pointed to a given file.
OUTPUT:
Enter data into file (type end to stop):
Hello
Hai
How r u
end
Reading data from file
Hello
Hai
How r u
end
Block read/write
It is useful to store the block of data into the file rather than individual
elements.Each block has some fixed size,it may be of strcture or of an
array.It is possible that a data file has one or more structures or arrays,So it
is easy to read the entire block from file or write the entire block to the
file.There are two useful functions for this purpose
1. fwrite():
This function is used for writing an entire block to a given file.
Syntax: fwrite( ptr, size, nst, fptr);
Where ptr is a pointer which points to the arrayof struture in which data is
written.
Size is the size of the structure
nst is the number of the structure
fptr is a filepointer.
Example program for fwrite():
Write a program to read an employee details and write them into the file at a
time using fwrite().
#include<stdio.h>
#include<conio.h>
void main()
{
struct emp
{
int eno;
char ename[20];
float sal;
}e;
FILE *fp;
fp=fopen("emp.dat", "wb");
clrscr();
printf("Enter employee number");
scanf("&d",&e.eno);
printf("Enter employee name");
fflush(stdin);
scanf("%s",e.ename);
printf("Enter employee salary");
scanf("%f",&e.sal);
fwrite(&e,sizeof(e),1,fp);
printf("One record stored successfully");
getch();
}
OUTPUT:
Enter employee num: 10
Enter employee name : seshu
Enter employee salary : 10000
One record stored successfully.
2. fread()
This function is used to read an entire block from a given file.
Syntax: fread ( ptr , size , nst , fptr);
Where ptr is a pointer which points to the array which receives structure.
Size is the size of the structure
nst is the number of the structure
fptr is a filepointer.
OUTPUT:
Employee number is 10
Employee name is seshu
Employee salary is 10000.
One record read successfully.
3. fprintf()
This function is same as the printf() function but it writes the data into the
file, so it has one more parameter that is the file pointer.
Syntax: fprintf(fptr, "controlcharacter",variable-names);
Where fptr is a file pointer
Control character specifies the type of data to be printed into file.
Variable-names hold the data to be printed into the file.
4. fscanf()
This function is same as the scanf() function but this reads the data from the
file, so this has one more parameter that is the file pointer.
Syntax: fscanf(fptr, "control character", &variable-names);
Where fptr is a file pointer
Control character specifies the type of data to be read from the file.
Address of Variable names are those that hold the data read from the file.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
int eno;
char ename[20];
float sal;
clrscr();
fp=fopen("emp.dat", "w+");
printf("Enter employee number");
scanf("&d",eno);
printf("Enter employee name");
fflush(stdin);
scanf("%s",ename);
printf("Enter employee salary");
scanf("%f",sal);
fprintf(fp, "%d %s %f\n",eno,ename,sal);
printf("Details of an employee are printed into file");
rewind(fp);
fscanf(fp,"%d %s %f",&eno,ename,&esal);
printf("Details of employee are\n");
printf("\n %d %s %f", eno,ename, sal);
fclose(fp);
getch();
}
OUTPUT:
Enter employee num: 10
Enter employee name : seshu
Enter employee salary : 10000
Details of an employee are printed into file.
Details of employee are
Employee number is 10
Employee name is seshu
Employee salary is 10000.
feof()
The macro feof() is used for detecting whether the file pointer is at the end
of file or not.It returns nonzero if the file pointer is at the end of the file
otherwise it returns zero.
Syntax: feof(fptr);
Where fptr is a file pointer .
ferror()
The macro ferror() is used for detecting whether an error occur in the file on
filepointer or not.It returns the value nonzero if an error,otherwise it returns
zero.
Syntax: ferror(fptr);
Where fptr is a file pointer.
Sequential and Random file access
1.Sequential Access: In this type of files data is kept in sequential order if
we want to read the last record of the file,we need to read all records before
that record so it takes more time.
2.Random Access : In this type of files data can be read and modified
randomly .If we want to read the last record we can read it directly.It takes
less time when compared to sequential file.
Example: Find Average of N numbers in File using Sequential Access
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
FILE *inFile;
char fname[30];
int sum,avg,num;
int n;
sum=0.0;
n=0;
printf("\nEnter a file name: ");
gets(fname);
inFile = fopen(fname, "r");
if (inFile == NULL)
{
printf("\nFailed to open file.\n");
exit(1);
}
while(!feof(inFile))
{
fscanf(inFile,"%d",&num);
printf("num=%d\n",num);
sum=sum+num;
n=n+1;
}
printf("\nSum=%d\n",sum);
avg=sum/n;
fclose(inFile);
printf("\nAverage=%d",avg);
getch();
return 0;
Output:
fseek():
This function is used for seeking the pointer position in the file at the
specified byte.
Syntax: fseek( file pointer, displacement, pointer position);
Where
file pointer ---- It is the pointer which points to the file.
displacement ---- It is positive or negative.This is the number of bytes which
are skipped backward (if negative) or forward( if positive) from the current
position.This is attached with L because this is a long integer.
pointer position:
This sets the pointer position in the file.
Ex:
1) fseek( p,10L,0)
0 means pointer position is on beginning of the file,from this statement
pointer position is skipped 10 bytes from the beginning of the file.
2)fseek( p,5L,1)
1 means current position of the pointer position.From this statement pointer
position is skipped 5 bytes forward from the current position.
3)fseek(p,-5L,1)
From this statement pointer position is skipped 5 bytes backward from the
current position.
ftell()
This function returns the value of the current pointer position in the file.The
value is count from the beginning of the file.
Syntax: ftell(fptr);
Where fptr is a file pointer.
rewind()
This function is used to move the file pointer to the beginning of the given
file.
Syntax: rewind( fptr);
Where fptr is a file pointer.
#include <stdio.h>
else
{
} // end else
getch();
return 0;
} // end main
Output:
/*
credit.txt file will be opened and data entered in output screen will get stored
in file.
*/
#include<stdio.h>
Output: