Showing posts with label fstream. Show all posts
Showing posts with label fstream. Show all posts

C++ Program to Count Characters, spaces, tabs and lines from a file

Leave a Comment
#include<iostream.h>
#include<fstream.h>
#include<conio.h>

void main()
{
FILE *fp;
//a pointer to file
char ch;
int nol=0,not=0,nos=0;nos=0;
//initializing by zero in order to avoid any garbage value
fp=fopen("test.c","r"); //open file test.c in read only mode
while(1)
{
ch=fgetc(fp);

//read each character of file in ch using pointer file pointer fp
if(ch==EOF) //if end of file in reached
break;
noc++;
//count number of characters
if(ch==' ')
//if space is read into ch increase its count
nos++;
if(ch='\n')

//if new line is read into ch increase its count
nol++;
if(ch=='\t')

//if tab is read increase its count
not++;
}

fclose(fp); //close file
printf("\n Number of Cahracters=%d",noc);
printf("\n Number of Spaces =%d",nos);
printf("\n Number of Tabs=%d",not);
printf("\n Number of Lines=%d",nol);

getche();
}
Read More...

Writing Data to Disk ( Files ) Using C++ Fstream Class

Leave a Comment
#include<iostream.h> 
#include<fstream.h>
#include<conio.h>

class emp
//Define Employee Class
{
protected:
char name[30];

int age;
float salary;
public :
void getemp()
{
cout<< "Enter Name:";
cin>>name;
cout<<"Enter Age:";
cin>>age;
cout<<"Enter Salary";
cin>>salary;

}
} ;

void main()
{
emp e;
//declaring object emp of employee class
e.getemp();
//Call getemp() function to input name, age and salary
ofstream outfile("Emp.dat");
//create Emp.dat file
outfile.write((char * )&emp,sizeof(emp));
//write contents of object emp to the file

getche();
}
Read More...