C and C++ Programming Resources

Share/Bookmark
Custom Search

File Handling in C Language

Posted on September 13th, 2008

Writing an object in a files

Since C++ is an object-oriented language, it is reasonable to wonder how objects can be written to and read from the disc. The program given below is intended to write an object in a file.

//program for writing objects in files
#include<fstream.h>
class employees
{
protected:
int empno;
char name[10];
char dept[5];
char desig[5];
double basic;
double deds;
public:
void getdata(void)
{coul<<endl<<"enter empno";cin>>empno;"
cout<<endl<<"enter empname";cin>>name;
cout<<endl<<"enter department ";
cin>>dept; cout<<endl<<"enter designation ";
cin>>desig; cout<<endl<<"enter basic pay ";cin>>basic:
cout<<endl<<"enter deds ";cin>>deds;
}
void main(void){
employees emp;
emp.getdata( );
ofstream outfile("f3.fil");
outfile. write((char * )&emp,sizeof(emp));
}

This program uses a class by name employees and an object by name emp. Data can be written only by the function inside the object. This program creates a binary data file by name f3.fil.The write( ) function is used for writing. The write( ) function requires two arguments, the address of the object to be written, and the size of the object in bytes. We use the size of operator to find the length of the emp object. The address of the object must be cast to type pointer to char.

Binary vs. Character files

You might have noticed that write( ) was used to output binary values, not just characters. To clarify, let us examine this further. Our emp object contained one int data member, three string data members and two double data members. The total number of bytes occupied by the data members comes to 38. It is as if write( ) took a mirror image of the bytes of information in memory and copied them directly to disc, without bothering any intervening translation or formatting. By contrast, the character based functions take some liberties with the data. for example, they expand the? \n ?character into a carriage return and a line feed before storing it to disk.

Reading object from file

The program given below is intended to read the file created in the above program.

//program f or reading data files
#include < istream.h>
class employees
{
protected:
int empno;
char name[I0]
char dept[5];
char desig[5];
double basic;
double deds;
public:
void showdata(void)
{cout<<endl<<"employeenumber: "<<empno;
cout<<endl<<"empname "<<name;
cout<<endl<<"department "<<dept;
cout<<endl<<"designation "<<desig;
cout<<endl<<"basic pay "<<basic:
cout<<endl<<"deds "<<deds;}
void main(void){
employees empl;
ifstream infile("f3.fil");
infile.read((char*)&empl, sizeof(empl));
empl.showdata( );
}

It may be noticed that both read( )and write( functions have similar argument. we must specify the address in which the disc input will be placed. We also use size of to indicate the number of bytes to be read.

The sample output looks as shown below:

employeenumber; 123
empname venkatesa
department elec
designation prog
basic pay 567.89
deds 45.76

Pages: [Page - 1] [Page - 2] [Page - 3] [Page - 4]

Tags: , ,

Like What you See?

Become one of the regulars by subscribing! You'll be the first to know when we add more great posts just like this. Join up by either RSS Feeds or Email Updates today!

There are 257 Comments to this post. You can follow any responses to this entry through the RSS 2.0 feed. You can skip to the end and leave a response or TrackBack from your own site.

  • Heart says:

    How do you write and read from a binary file using the C Language?.?

  • sunaina says:

    imagine we have a file that has the following text:
    Two, one, 2,
    One fish, two fish?!?
    red_fish; BLUE FISH!!!

    how can I ignore all non-alphabetic characters and print the alphabetic characters to standard output – each word on a line by itself, with all the letters converted to lower case
    output should be:
    one
    two
    one
    one
    fish
    two
    fish
    red
    fish
    blue
    fish
    Kindly let me know at the earliest and email to sunainabansal2003@yahoo.com
    thank u

  • Tabish says:

    i want to show data which is store in a doc file please help me if any one have code for this.
    tabishahmad1@gmail.com
    please mail me.

  • kanu says:

    bubble sorting using register and timer and restart the sorting again where stop

  • Mathews says:

    How to convert the contents of a file to upper case. file may contain bopth alphabetic and non-alphabetic characters.

  • antonisl says:

    Hi,could you please help me with this:
    “Write program in C which it will accept from the user the name of file of text and stores the characters that are found in the odd places in the file “odd.txt” and those that find in even in “even.txt”.”

  • martz says:

    -create a program that will compute the running time of another program, not showing the running
    time in seconds but by number of (Tfetch, Tstore, Tdelete, etc.) or any related running time axioms..

    COULD SOMEONE HELP ME WITH THIS PROBLEM????…
    hoping for your kind response…
    just send to my email: canon_martina@yahoo.com.ph

  • martinnitram says:

    please i need help in two or three days about this c problem; develop a simple user authentication system using C language. The system should allow you to register usernames into a file and then check if the user is valid. Remember that to check the validity of the user, you must first enter the username of that user and the system checks if this user exists in the file that stores the users. If a wrong username is supplied to the system, it should display to you an appropriate message, for example “Invalid User”. When you are through with authentication, the system should display all the users stored in the file. you can kindly post your reply to aine.brian@yahoo.com

  • vikibe says:

    Hi, i want to delete a line in a file and replace it with another line.can i use the file pointer or help me?

  • supriya says:

    hi…can anyone help me in writing a c program to delete a particular word from file thnks in advance

  • vinnu says:

    hi…..all
    write a program i c without using main().how posssibbe? if anybody has know pls send me answer with code on my email address.vinay.intech@rediffmail.com this question
    is a infosys software system

  • chinmayee says:

    hi can anyone help me with this problem does anyone know how password is hidden and typed as a dot using file handling plz do reply at cbaitharu@yahoo.co.in

  • #include<stdio.h>
    
    main()
    {
    
    		FILE *sp, *tp;
    		char ch,nextch;
    		int index = 0;
    
    		sp = fopen("d:\hello1.txt","r");
    		tp = fopen("d:\remove.txt","w");
    
    		if(sp == NULL)
    		{
    			perror("Cannot Open Source File");
    			return 0;
    		}
    
    		while( (ch = fgetc(sp)) != EOF)
    		{
    				if(ch == 10)
    				{
    					index++;
    					nextch = fgetc(sp);
    
    					if(ch == 10 && nextch != 10)
    					{
    						fputc(ch, tp);
    						fputc(nextch, tp);
    					}
    
    				}
    
    				if(ch != 10)
    				{
    					fputc(ch,tp);
    					index++;
    				}
    
    		}
    
    }
  • aman says:

    Hey see there are three more modes to open a file that are w+ : use to open a file which can be both read and write
    r+ : use to open a file in which we can write more with also doing alteration in before written data
    a+ : this is used to read and write data but wihtout doing alteration in existing data in file if file already exists
    for creating numeric data files we have to open them in binary mode like if we want to read an existing file we will use mode that is “rb”
    eg: fp=fopen(“abc”,”rb”);
    same for write mode

  • jai says:

    you better give the format of the file. otherwise it will be difficult
    ——– Original Message ——–

    ——– Original Message ——–
    hello. please send to me a code to sort the contents of file…..thank alot

  • ashley says:

    i want to do a database using file handling in cpp.its a music shoppe database..plz help


Leave a Reply

You must be logged in to post a comment.