How to write a Program that reads a file first.txt and creates a new file second.txt which contains only those words from first.txt which starts from lower-case vowels.
C++ Data File Handling Program |
//Program that reads a file first.txt and creates a new file second.txt which contains only those words from first.txt which starts from lower-case vowels.
/*first.txt:-
*/
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<ctype.h>
void main()
{
clrscr();
char a[80];
ifstream ifile("first.txt");
ofstream ofile("second.txt");
while(!ifile.eof())
{
ifile>>a;
if((a[0]=='a')||(a[0]=='e')||(a[0]=='i')||(a[0]=='o')||(a[0]=='u'))
ofile<<a;
}
getch();
}
What is a File ?
• A file is a stream of bytes stored on some secondary storage devices.
• Text file: A text file stores information in readable and printable form. Each line of text is
terminated with an EOL End of Line cha racter.
• Binary file: A binary file contains information in the non-readable form i.e. in the same
format in which it is held in memory
There are three file I/O classes used for file read / write operations.
- ifstream - can be used for read operations.
- ofstream - can be used for write operations.
- fstream - can be used for both read & write operations.
fstream.h:
• This header file includes the definitions for the stream classes ifstream, ofstream and
fstream. In C++ file input output facilities implemented through fstream.h header file.
• It contain predefines set of operation for handling file related input and output, fstream
class ties a file to the program for input and output operation.
• A file can be opened using:
o By the constructor method. This will use default streams for file input or output.
This method is preferred when file is opened in input or output mode only.
Example : ofstream file“student.dat”); or ifstream file“student.dat”);
o By the open member function of the stream. It will preferred when file is
opened in various modes i.e ios::in, ios::out, ios::app, ios::ate etc.
e.g fstream file;
file.open “book.dat”, ios::in | ios::out | ios::binary);
File modes:
• ios::out It open file in output mode i.e write mode and place the file
pointer in beginning, if file already exist it will overwrite the file.
• ios::in It open file in input moderead mode and permit reading from the file.
• ios::app It open the file in write mode, and place file pointer at the end of file i.e to
add new contents and retains previous contents. If file does not
exist it will create a new file.
• ios::ate It open the file in write or read mode, and place file pointer at the end of
file i.e input/ output operations can performed anywhere in the file.
• ios::trunc It truncates the existing file (empties the file.
• ios::nocreate If file does not exist this file mode ensures that no file is
created and open fails.
• ios::noreplace If file does not exist, a new file gets created but if the file
already exists, the open( fails.
• ios::binary Opens a file in binary mode.