Wednesday 12 July 2017

Text File Handling

A file is a bunch of bytes stored on some storage device like disk.

Need: To store data permanently and in large quantities.

Types of data files:

Text file and binary file.

A text file is also called as an ascii file. Character conversions take place in the text file and it includes EOL end of line marker at the end of every line.

No such conversions take place in binary file. It saves data in binary form .A binary file is a file stored in binary format. A binary file is computer-readable but not human-readable. All executable programs are stored in binary files, as are most numeric data files. In contrast, text files are stored in a form (usually ASCII) that is human-readable.


Stream - sequence of bytes - acts as an interface between program and I/O devices.

Stream that reads data from the file - Input stream

Stream that writes data on to the file - output stream.

Classes for file stream operations

I/O system of C++ contain as set of classes that defines file handling methods. This includes fstream, ifstream, ofstream.

iostream.h -> related to console I/O
fstream.h-> related to file I/O

Declaring a file stream
File Stream is a data type which is used to declare an object of stream. It may be input file stream or output file stream.

Syntax
file_stream_class  stream_object;

eg:ifstream fin;// for input operation
     ofstream fout;// for outupt operation

Opening a file

Before a file is used, it should be opened. There are 2 methods to open a file.

i) By using constructor function of the class
       ifstream f1("story.txt");
ii) By using open method.

    ifstream f1;
    f1.open("story.txt");

Steps to read a text file and process it

i) Declare the stream(ifstream or fstream)
ii) Determine the buffer size
iii) Declare and initialize variables if any
iv) check if file exists, otherwise display error message
v) use while loop(to check end of file condition)
vi) determine the input method(to get the content into the buffer)
     for eg if f1 is the object
     f1.get(ch);// will get a single character from the file
     f1.get(ch,50);// will get ch as a string from the file
     f1>>ch;// will get ch as a string thereby ignoring space and other whiteline characters
     f1.getline(ch,50);// will get one line of content at a time in the buffer
v) check for condition if any and process(using ctr)
vi) end the loop
vii) Print the required output

Steps to write data on to text file  

i) Declare the stream(ofstream or fstream)
ii) Determine the buffer size
iii) Declare and initialize variables if any
iv) use do while loop
v) Input values from user within the body
vi) use one of the following to write the values into the file
    if f1 is the object
      f1<<str;// will write str as string into f1
      f1.put(str);// will write str as a single character into the file.
vii) input continue variable
viii) end the while loop


Different file modes

ios::in - to read the file
ios::out - to write the file
ios::app - to add data at the end of the file
ios::ate- to write data anywhere in the file
ios::nocreate - open fails if file does not exist
ios::noreplace - open fails if file already exists
ios::trunc - deletes contents of file if exists
ios::binary - opens file in binary mode

random reading of files

f1.seekg(5,ios::beg);// moves file pointer 5 bytes forward starting from the beginning of the file.
f1.seekg(-5,ios::cur); // moves file pointer backwards from the current position.
f1.seekg(0,ios::end); moves the file pointer to end of file position.
f1.tellg();// tells the location of the pointer in the file
f1.seekp();// places the file pointer before writing
f1.tellp();// tells the location of the pointer while writing (if the object is opened in the output mode)

Exercises:

1)       Write a program that accepts a file name as a variable and displays the size of a file in bytes.    
2)       Write a function COUNT() to count the presence of a word “to” as independent word in a text file “NOTES.TXT”.                                                       
For eg: if the content of the file contains
It is very important to know that
Smoking is an injurious tool to health
Let us take initiative to stop it.

The output should be:
Count of “to”: 3    

3)       Write a program using a  function to count the number of alphanumeric words present in a text file:             
For eg, if the file contains
Attention 12C students, the vehicle no TN9022 is parked wrongly at B3.
The output should be :3

4)       Write programs(using functions) to
a)       Read a text file story.txt and count no of alphabets, digits and special characters in that file and display the same.
b)       Read a text file lines.txt and prints count of lines that has the word “you” in a line.
For eg:
If the file has
Take risks in life.
If you win, you can lead!
If you lose, you can guide!

Output: 2

#include <fstream.h>
#include <string.h>
#include <conio.h>
void main()
{
ifstream f1("dream.txt");
char str[25];
int ctr=0;
while(!f1.eof())
{f1>>str;
 if(strcmpi(str,"you")==0)
 {
 ctr++;
 f1.getline(str,25);
 }
}
cout<<ctr;

}

c)       Read a text file case.txt and convert all the text to upper case and write it in another file uppercase.txt
For eg if the file contains following text:
Dream, dream, dream
Dreams transform into thoughts and thoughts result in action.

The output file should contain
FOR EG IF THE FILE CONTAINS FOLLOWING TEXT:
DREAM, DREAM, DREAM DREAMS TRANSFORM INTO THOUGHTS AND THOUGHTS RESULT IN ACTION.  

Solution:
#include <fstream.h>
#include <string.h>
#include <conio.h>
void main()
{
ifstream f1("dream.txt");
ofstream f2("out.txt");
char str[25];
while(!f1.eof())
{f1>>str;
 f2<<strupr(str)<<" ";
}}


d)       Read the text file WORDS.TXT and print those words that does not end with a vowel.
Eg: If the file contains

If you want to shine like a sun, first burn like a sun.

Output:
If want sun first burn sun

e)       Read a text file story.txt and print all three letter words starting with a capital letter.
f)        Read  a text file called lines.txt and print all the strings that are palindromes.
        (Hint: Use strrev() function)

Note: A palindrome is a string that is same as its reverse. Eg: madam


Predict the output problem given the following code assuming the text file contains the following content:

she sells sea shells in the sea shore.

The code:

#include <fstream.h>
#include <string.h>
#include <conio.h>
void main()
{
clrscr();
ifstream f1("dream.txt");
char s[20],ch;
f1.seekg(1);
f1>>ch;
cout<<ch<<endl;
f1.seekg(4);
f1.seekg(10);
f1.get(s,10);
cout<<s<<endl;
f1.seekg(-15,ios::end);
f1.getline(s,20);
cout<<s<<endl;

}

Output:


h

sea shell

 the sea shore.

Identify the errors in the following code and rewrite the corrected code and underline it.
(Assume necessary header files are included).

void main()
{
clrscr();
ifstream f1("dream.txt",ios::in);
char s[30]="Honesty is the best policy";
f1<<s;
f1.seekg(0);
f1.gets(s);
while(f1)
{
f1.get(s);
if(strcmp(s,"to")==0) ctr++;
}

}

Solution


void main()
{
clrscr();
fstream f1("dream.txt",ios::in|ios::out);
char s[30]="Honesty is the best policy";
int ctr=0;
f1<<s;
f1.seekg(0);
f1.get(s,20);
while(f1)
{
f1.get(s,20);
if(strcmp(s,"to")==0) ctr++;
}
}

BOARD PAPER - 2017

Write function definition for SUCCESS( ) in C++ to read the content of a text file
STORY.TXT, count the presence of word SUCCESS and display the number of
occurrence of this word. 2
Note :
– The word SUCCESS should be an independent word
– Ignore type cases (i.e. lower/upper case)
Example :
If the content of the file STORY.TXT is as follows :
Success shows others that we can do it. It is possible to achieve success with hard work. Lot of money does not mean SUCCESS.
The function SUCCESS( ) should display the following :

3

Ans:

void SUCCESS()
{
int count=0;
ifstream f("STORY.TXT");
char s[20];
while (!f.eof())
{

f>>s;
count++;
}
cout<<count;
f.close();

}


No comments:

Post a Comment