Page 1 :
www.ncrtsolutions.in, , DATA FILE HANDLING IN C++, 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., File Stream, • Stream: A stream is a general term used to name flow of data. Different streams are used, to represent different kinds of data flow., • There are three file I/O classes used for file read / write operations., o ifstream, can be used for read operations., o ofstream, can be used for write operations., o 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., eof: This function determines the end-of-file by returning truenon -zero) for end of file, otherwise returning falsezero)., close: This function terminates the connection between the file and stream associated with it., Stream_object.close; e.g file.clos e;, Text File functions:, Char I/O :, get – read a single character from text file and store in a buffer., e.g file.getch;, put - writing a single character in textfile e.g. file.putch;, getline - read a line of text from text file store in a buffer., e.g file.getlines,80);, 39, Material Downloaded From http://www.ncrtsolutions.in
Page 2 :
, , www.ncrtsolutions.in, , We can also use file>>ch for reading and file<<ch writing in text file. But >> operator, does not accept white spaces., , Binary file functions:, read - read a block of binary data or reads a fixed number of bytes from the specified, stream and store in a buffer., Syntax : Stream_object.read(char *& Object, sizeofObject;, e.g file.read(char *&s, sizeofs);, write – write a block of binary data or writes fixed number of bytes from a specific, memory location to the specified stream., Syntax : Stream_object.writechar *)& Object, sizeofObject;, e.g file.writechar *)&s, sizeofs);, Note:, Both functions take two arguments., • The first is the address of variable, and the second is the length of that variable in bytes. The, address of variable must be type cast to type char*pointer to character type, • The data written to a file using write ) can only be read accurately using read( )., , File Pointer: The file pointer indicates the position in the file at which the next input/output is to, occur., Moving the file pointer in a file for various operations viz modification, deletion , searching, etc. Following functions are used:, seekg(: It places the file pointer to the specified position in input mode of file., e.g file.seekg(p,ios::beg); or file.seekg -p,ios::end, or file.seekg(p,ios::cur, i.e to move to p byte position from beginning, end or current position., seekp: It places the file pointer to the specified position in output mode of file., e.g file.seekpp,ios::beg); or file.seekp -p,ios::end, or file.seekpp,ios::cur, i.e to move to p byte position from beginning, end or current position., tellg(: This function returns the current working position of the file pointer in the input mode., e.g int p=file.tellg(;, tellp: This function returns the current working position of the file pointer in the output mode., e.f int p=file.tellp;, Steps To Create A File, Declare an object of the desired file stream class(ifstream, ofstream, or fstream, Open the required file to be processed using constructor or open function., Process the file., Close the file stream using the object of file stream., General program structure used for creating a Text File, To create a text file using strings I/O, #include<fstream.h> //header file for file operations, void main(, {, char s[80], ch;, ofstream file“myfile.txt”; //open myfile.txt in default output mode, do, {, cout<<” n enter line of text”;, gets(s; //standard input, file<<s; // write in a file myfile.txt, cout<<” n more input y/n”;, 40, Material Downloaded From http://www.ncrtsolutions.in
Page 4 :
if islowerch), count++;, }, Fin.close;, return count;, , www.ncrtsolutions.in, , }, , Function to calculate the average word size of a text file., void calculate, { fstream File;, File.open(“book.txt”,ios::in);, char a[20];, char ch;, int i=0,sum=0,n=0;, whileFile, { File.getch;, a[i]=ch;, i++;, ifch==’ ‘ || ch== ‘.’||char==’,’ch==’, t’||ch==’ n’, {i --; sum=sum +i;, i=0; N++;, }, }, cout<<”average word size is “<<sum/n);, }, , Assume a text file “coordinate.txt” is already created. Using this file create a C++ function, to count the number of words having first character capital., int countword(, {, ifstream Fin(“BOOK.txt”;, char ch[25];, int count=0;, while!Fin.eof, {Fin>>ch;, if (isupperch[0], count++;, }, Fin.close;, return count;, }, , Function to count number of lines from a text files a line can have maximum 70 characters, or ends at ‘.’, int countword(, {, ifstream Fin(“BOOK.txt”;, char ch[70];, int count=0;, if (!Fin), {, cout<<”Error opening file!” ;, exit0);, }, 42, Material Downloaded From http://www.ncrtsolutions.in
Page 5 :
while1), {Fin.getlinech,70,‘.’;, if (Fin.eof, break;, count++;, }, Fin.close;, return count;, }, , www.ncrtsolutions.in, , 2/3 Marks Practice Questions, 1. Write a function in C++ to count the number of uppercase alphabets present in a text file, “BOOK.txt”, 2. Write a function in C++ to count the number of alphabets present in a text file, “BOOK.txt”, 3. Write a function in C++ to count the number of digits present in a text file “BOOK.txt”, 4. Write a function in C++ to count the number of white spaces present in a text file, “BOOK.txt”, 5. Write a function in C++ to count the number of vowels present in a text file “BOOK.txt”, 6. Assume a text file “Test.txt” is already created. Using this file, write a function to create, three files “LOWER.TXT” which contains all the lowercase vowels and “UPPER.TXT”, which contains all the uppercase vowels and “DIGIT.TXT” which contains all digits., General program structure used for operating a Binary File, Program to create a binary file ‘student.dat’ using structure., #include<fstream.h>, struct student, {, char name[15];, float percent;, };, void main(, {, ofstream fout;, char ch;, fout.open(“student.dat”, ios::out | ios:: binary;, clrscr;, student s;, if!fout, {, cout<<“File can’t be opened”;, break;, }, do, {, cout<<” n enter name of student”;, gets(s;, cout<<” n enter persentage”;, cin>>percent;, fout.writechar *&s,sizeofs); // writing a record in a student.dat file, cout<<” n more record y/n”;, cin>>ch;, }whilech!=’n’ || ch!=’N’;, fout.close;, }, 43, Material Downloaded From http://www.ncrtsolutions.in