CPP - Files and Templates

 

CPP

Files and Templates



Fill in the blanks

1.Write a Template Syntax  template   <class type>

2.What is files header file in C++?  <fstream.h>

3.fstream has ofstream , ifstream

4.Write a syntax for append mode  ios::app

5. ios:: ate means End of file

6.Files used for Permanent storage of data

7.tellp() means current position of the put pointer

8.tellg() means current position of the get pointer

9.seek() means moves specified location

10.ios::in is reading mode , ios::out is writing mode

 

 

Answer the following Question

                                                                              (4 marks)

          1.Write a Program for Writing and Reading a data into file program

#include<iostream.h>

#include<conio.h>

#include<string.h>

#include<fstream.h>

void main()

{

    char string[80];

    clrscr();

    cout<<"Enter a string";

    cin>>string;

    int len=strlen(string);

    fstream file;

    file.open("sample.txt",ios::in|ios::out);

         for(int i=0;i<len;i++)

         file.put(string[i]);

         file.seekg(0);

         char ch;

         while(file)

         {

             file.get(ch);

             cout<<ch;

         }

         getch();

}

          2.Write a Program for appending a data into file

#include<iostream.h>

#include<fstream.h>

#include<conio.h>

void main()

{

 

    char str[50] = "Welcome to traineetech!";

    char ch;

    fstream fstream_ob;

    fstream_ob.open("File.txt", ios::app);

    fstream_ob<< str << "\n";

    fstream_ob.close();

    getch();

}

          3.Write a Program to Write a File

#include<iostream.h>

#include<fstream.h>

#include<conio.h>

void main()

{

int empno,empsal;

char empname[25];

clrscr();

ofstream fp;

fp.open("file.txt");

cout<<"enter employee number :";

cin>>empno;

cout<<"enter employee name:";

cin>>empname;

cout<<"enter employee salary:";

cin>>empsal;

fp<<empno<<"\n";

fp<<empname<<"\n";

fp<<empsal<<"\n";

fp.close();

getch();

}

          4. Write a Program to Read a File

#include<iostream.h>                       

#include <fstream.h>      

#include<conio.h>

void main() {

    fstream FileName; 

    clrscr();

    FileName.open("cs.txt", ios::in);        

    if (!FileName) {                       

        cout<<"File doesn’t exist.";         

    }

    else {

        char x;                    

        while (1) {        

            FileName>>x;             

            if(FileName.eof())         

                break;             

            cout<<x;                 

        }

    }

    FileName.close();                  

   getch();

}


          5.Write a Program for Function Template

#include<iostream.h>

#include<conio.h>

template<class T>

T max(T  x,T  y)

{

return (x>y)?x:y;

}

void main()

{

clrscr();

cout<<max(17,19)<<endl;

cout<<max(1.5,6.7)<<endl;

cout<<max(‘A’,’B’)<<endl;

getch();

}

 

No comments:

Post a Comment