Translate

Data File Handling In C++


Data File Handling In C++ download
File. The information / data stored under a specific name on a storage device, is called a file.
Stream. It refers to a sequence of bytes.
Text file. It is a file that stores information in ASCII characters. In text files, each line of text is terminated with a special character known as EOL (End of Line) character or delimiter character. When this EOL character is read or written, certain internal translations take place.
Binary file. It is a file that contains information in the same format as it is held in memory. In binary files, no delimiters are used for a line and no translations occur here.    
Classes for file stream operation
ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.
Opening a file
OPENING FILE USING CONSTRUCTOR
ofstream outFile("sample.txt");    //output only
ifstream inFile(“sample.txt”);  //input only
OPENING FILE USING open()
Stream-object.open(“filename”, mode)
      ofstream outFile;
      outFile.open("sample.txt");
     
 
      ifstream inFile;
      inFile.open("sample.txt");
File mode parameter
Meaning
ios::app
Append to end of file
ios::ate
go to end of file on opening
ios::binary
file open in binary mode
ios::in
open file for reading only
ios::out
open file for writing only
ios::nocreate
open fails if the file does not exist
ios::noreplace
open fails if the file already exist
ios::trunc
delete the contents of the file if it exist
All these flags can be combined using the bitwise operator OR (|). For example, if we want to open the file example.bin in binary mode to add data we could do it by the following call to member function open():
fstream file; 
file.open ("example.bin", ios::out | ios::app | ios::binary);
Closing File
   outFile.close();
   inFile.close();
INPUT AND OUTPUT OPERATION
put() and get() function
the function put() writes a single character to the associated stream. Similarly, the function get() reads a single character form the associated stream.
example :
file.get(ch);
file.put(ch);
write() and read() function
write() and read() functions write and read blocks of binary data.
example:
file.read((char *)&obj, sizeof(obj));
file.write((char *)&obj, sizeof(obj));
ERROR HANDLING FUNCTION
FUNCTION
RETURN VALUE AND MEANING
eof()
returns true (non zero) if end of file is encountered while reading; otherwise return false(zero)
fail()
return true when an input or output operation has failed
bad()
returns true if an invalid operation is attempted or any unrecoverable error has occurred.
good()
returns true if no error has occurred.



File Pointers And Their Manipulation
All i/o streams objects have, at least, one internal stream pointer: 
ifstream, like istream, has a pointer known as the get pointer that points to the element to be read in the next input operation.
ofstream, like ostream, has a pointer known as the put pointer that points to the location where the next element has to be written.
Finally, fstream, inherits both, the get and the put pointers, from iostream (which is itself derived from both istream and ostream). 

These internal stream pointers that point to the reading or writing locations within a stream can be manipulated using the following member functions:
seekg()
moves get pointer(input) to a specified location
seekp()
moves put pointer (output) to a specified location
tellg()
gives the current position of the get pointer
tellp()
gives the current position of the put pointer

The other prototype for these functions is:
seekg(offset, refposition ); 
seekp(offset, refposition );
The parameter offset represents the number of bytes the file pointer is to be moved from the location specified by the parameter refposition. The refposition takes one of the following three constants defined in the ios class.
ios::beg          start of the file
ios::cur          current position of the pointer
ios::end          end of the file
example:
file.seekg(-10, ios::cur);



Basic Operation On Text File In C++ download

File I/O is a five-step process:
1. Include the header file fstream in the program.
2. Declare file stream object.
3. Open the file with the file stream object.
4. Use the file stream object with >>, <<, or other input/output functions.
5. Close the files.
Following program shows how the steps might appear in program.

 

Program to write in a text file

 
#include <fstream>
using namespace std;
 
int main()
{
    ofstream fout;
    fout.open("out.txt");
    
    char str[300] = "Time is a great teacher but 
            unfortunately it kills all its pupils. Berlioz";
 
    //Write string to the file.
    fout << str;
 
    fout.close();
    return 0;
}
 


Program to read from text file and display it

 
#include<fstream>
#include<iostream>
using namespace std;
 
int main()
{
    ifstream fin;
    fin.open("out.txt");
    
    char ch;
    
    while(!fin.eof())
    {
         fin.get(ch);
         cout << ch;
    }
    
    fin.close();
    return 0;
}
 

Program to count number of characters.

 
#include<fstream>
#include<iostream>
using namespace std;
 
int main()
{
    ifstream fin;
    fin.open("out.txt");
 
    int count = 0;
    char ch; 
 
    while(!fin.eof())
    {
        fin.get(ch);
        count++;
    }
    
    cout << "Number of characters in file are " << count;
    
    fin.close();
    return 0;
}
 


Program to count number of words

 
#include<fstream>
#include<iostream>
using namespace std;
 
int main()
{
    ifstream fin;
    fin.open("out.txt");
 
    int count = 0;
    char word[30]; 
 
    while(!fin.eof())
    {
        fin >> word;
        count++;
    }
    
    cout << "Number of words in file are " << count;
    
    fin.close();
    return 0;
}
 

Program to count number of lines

 
#include<fstream>
#include<iostream>
using namespace std;
 
int main()
{
    ifstream fin;
    fin.open("out.txt");
 
    int count = 0;
    char str[80];
    
    while(!fin.eof())
    {
        fin.getline(str,80);
        count++;
    }
    
    cout << "Number of lines in file are " << count;
  
    fin.close();
    return 0;
}

Program to copy contents of file to another file.

 
#include<fstream>
using namespace std;
 
int main()
{
    ifstream fin;
    fin.open("out.txt");
    
    ofstream fout;
    fout.open("sample.txt");
    
    char ch;
    
    while(!fin.eof())
    {
        fin.get(ch);
        fout << ch;
    }
 
    fin.close();
    fout.close();
    return 0;
}

 

Basic Operation On Binary File In C++

When data is stored in a file in the binary format, reading and writing
data is faster because no time is lost in converting the data from one format to another format. Such files are called binary files. This following program explains how to create binary files and also how to read, write, search, delete and modify data from binary files.
#include<iostrea.h>
#include<fstream.h>
#include<cstdio.h>
 
class Student
{
    int admno;
    char name[50];
public:
    void setData()
    {
        cout << "\nEnter admission no. ";
        cin >> admno;
        cout << "Enter name of student ";
        cin.getline(name,50);
    }
 
    void showData()
    {
        cout << "\nAdmission no. : " << admno;
        cout << "\nStudent Name : " << name;
    }
        
    int retAdmno()
    {
        return admno;
    }
};
 
/*
* function to write in a binary file.
*/
 
void write_record()
{
    ofstream outFile;
    outFile.open("student.dat", ios::binary | ios::app);
 
    Student obj;
    obj.setData();
    
    outFile.write((char*)&obj, sizeof(obj));
    
    outFile.close();
}
 
/*
* function to display records of file
*/
 
 
void display()
{
    ifstream inFile;
    inFile.open("student.dat", ios::binary);
 
    Student obj;
    
    while(inFile.read((char*)&obj, sizeof(obj)))
    {
        obj.showData();
    }        
    
    inFile.close();
}
 
/*
* function to search and display from binary file
*/
 
void search(int n)
{
    ifstream inFile;
    inFile.open("student.dat", ios::binary);
    
    Student obj;
 
    while(inFile.read((char*)&obj, sizeof(obj)))
    {
        if(obj.retAdmno() == n)
        {
            obj.showData();
        }
    }
    
    inFile.close();
}
 
/*
* function to delete a record
*/
 
void delete_record(int n)
{
    Student obj;
    ifstream inFile;
    inFile.open("student.dat", ios::binary);
 
    ofstream outFile;
    outFile.open("temp.dat", ios::out | ios::binary);
    
    while(inFile.read((char*)&obj, sizeof(obj)))
    {
        if(obj.retAdmno() != n)
        {
            outFile.write((char*)&obj, sizeof(obj));
        }
    }
 
    inFile.close();
    outFile.close();
    
    remove("student.dat");
    rename("temp.dat", "student.dat");
}
 
/*
* function to modify a record
*/
 
void modify_record(int n)
{
    fstream file;
    file.open("student.dat",ios::in | ios::out);
 
    Student obj;
 
    while(file.read((char*)&obj, sizeof(obj)))
    {
        if(obj.retAdmno() == n)
        {
            cout << "\nEnter the new details of student";
            obj.setData();
            
            int pos = -1 * sizeof(obj);
            file.seekp(pos, ios::cur);
                    
            file.write((char*)&obj, sizeof(obj));
        }
    }
  
    file.close();
}
 
int main()
{
    //Store 4 records in file
    for(int i = 1; i <= 4; i++)
       write_record();
          
    //Display all records
    cout << "\nList of records";
    display();
       
    //Search record
    cout << "\nSearch result";
    search(100);
       
    //Delete record 
    delete_record(100);
    cout << "\nRecord Deleted";
       
    //Modify record
    cout << "\nModify Record 101 ";
    modify_record(101);
       
    return 0;
}

How to Earn money Online in just one minute

How to Earn money Online in just one minute
This method is based on earning from click on ads published on your site, web pages, forum or any apps. I have already discuss about cpc in my article about ads. If you want to learn more in details about cpc must read my article about ways to make money from ads.

The following best cost per click networks which offers best rates for every click are
  1. Google Adsense:-  It one of biggest and popular trusted network by everyone. Google Adsense Offers Highest CPC and CPM rates. But its earning is totally depend on your visitors location and CTR also. It not so easy to get approval of adsense.
  2. Media.net :- This is new network form by partnership of yahoo and bing with media.net. It is good competitor of adsense. It offers good CPC rates as compare to others.
  3. Chitika:- It is also most popular network for CPC. It also offers best revenue from ads but slightly lesser than Adsense
  4. Infolinks:- It is one the best program for text based ads. It offers good revenue for In-text link ads and for other banner ads also.
  5. Bidvertiser:- It is also relative good as compare to others but its is lesser as compare to above programs. But Still it is best one.

C++ Tutorial Overloading (Operator and Function)

C++ Tutorial

C++ Overloading (Operator and Function)
C++ allows you to specify more than one definition for a function name or an operator in the same scope, which is called function overloading and operator overloading respectively.
An overloaded declaration is a declaration that had been declared with the same name as a previously declared declaration in the same scope, except that both declarations have different arguments and obviously different definition (implementation).
When you call an overloaded function or operator, the compiler determines the most appropriate definition to use by comparing the argument types you used to call the function or operator with the parameter types specified in the definitions. The process of selecting the most appropriate overloaded function or operator is called overload resolution.

Function overloading in C++:

You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You can not overload function declarations that differ only by return type.
Following is the example where same function print() is being used to print different data types:
#include <iostream>
using namespace std;
 
class printData 
{
   public:
      void print(int i) {
        cout << "Printing int: " << i << endl;
      }
 
      void print(double  f) {
        cout << "Printing float: " << f << endl;
      }
 
      void print(char* c) {
        cout << "Printing character: " << c << endl;
      }
};
 
int main(void)
{
   printData pd;
 
   // Call print to print integer
   pd.print(5);
   // Call print to print float
   pd.print(500.263);
   // Call print to print character
   pd.print("Hello C++");
 
   return 0;
}
When the above code is compiled and executed, it produces the following result:
Printing int: 5
Printing float: 500.263
Printing character: Hello C++

Operators overloading in C++:

You can redefine or overload most of the built-in operators available in C++. Thus a programmer can use operators with user-defined types as well.
Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined. Like any other function, an overloaded operator has a return type and a parameter list.
Box operator+(const Box&);
declares the addition operator that can be used to add two Box objects and returns final Box object. Most overloaded operators may be defined as ordinary non-member functions or as class member functions. In case we define above function as non-member function of a class then we would have to pass two arguments for each operand as follows:
Box operator+(const Box&, const Box&);
Following is the example to show the concept of operator over loading using a member function. Here an object is passed as an argument whose properties will be accessed using this object, the object which will call this operator can be accessed using this operator as explained below:
#include <iostream>
using namespace std;
 
class Box
{
   public:
 
      double getVolume(void)
      {
         return length * breadth * height;
      }
      void setLength( double len )
      {
          length = len;
      }
 
      void setBreadth( double bre )
      {
          breadth = bre;
      }
 
      void setHeight( double hei )
      {
          height = hei;
      }
      // Overload + operator to add two Box objects.
      Box operator+(const Box& b)
      {
         Box box;
         box.length = this->length + b.length;
         box.breadth = this->breadth + b.breadth;
         box.height = this->height + b.height;
         return box;
      }
   private:
      double length;      // Length of a box
      double breadth;     // Breadth of a box
      double height;      // Height of a box
};
// Main function for the program
int main( )
{
   Box Box1;                // Declare Box1 of type Box
   Box Box2;                // Declare Box2 of type Box
   Box Box3;                // Declare Box3 of type Box
   double volume = 0.0;     // Store the volume of a box here
 
   // box 1 specification
   Box1.setLength(6.0); 
   Box1.setBreadth(7.0); 
   Box1.setHeight(5.0);
 
   // box 2 specification
   Box2.setLength(12.0); 
   Box2.setBreadth(13.0); 
   Box2.setHeight(10.0);
 
   // volume of box 1
   volume = Box1.getVolume();
   cout << "Volume of Box1 : " << volume <<endl;
 
   // volume of box 2
   volume = Box2.getVolume();
   cout << "Volume of Box2 : " << volume <<endl;
 
   // Add two object as follows:
   Box3 = Box1 + Box2;
 
   // volume of box 3
   volume = Box3.getVolume();
   cout << "Volume of Box3 : " << volume <<endl;
 
   return 0;
}
When the above code is compiled and executed, it produces the following result:
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400

Overloadable/Non-overloadableOperators:

Following is the list of operators which can be overloaded:
+
-
*
/
%
^
&
|
~
!
,
=
< 
> 
<=
>=
++
--
<< 
>> 
==
!=
&&
||
+=
-=
/=
%=
^=
&=
|=
*=
<<=
>>=
[]
()
->
->*
new
new []
delete
delete []
Following is the list of operators, which can not be overloaded:
::
.*
.
?:

Operator Overloading Examples:

Here are various operator overloading examples to help you in understanding the concept.
S.N.
Operators and Example
1
Unary operators overloading
2
Binary operators overloading
3
Relational operators overloading
4
Input/Output operators overloading
5
++ and -- operators overloading
6
Assignment operators overloading
7
Function call () operator overloading
8
Subscripting [] operator overloading
9
Class member access operator -> overloading