Monday, June 19, 2023

Files in Cpp

 

Files

Files store data permanently in a storage device. With file handling, the output from a program can be stored in a file.

#include<fstream.h>

 


syntax

open (file_name, mode);
 

Value

Description

ios:: app

The Append mode. The output sent to the file is appended to it.

ios::ate

It opens the file for the output then moves the read and write control to file’s end.

ios::in

It opens the file for a read.

ios::out

It opens the file for a write.

ios::trunk

If a file exists, the file elements should be truncated prior to its opening.

 

C++ Files and Streams

Data Type

Description

fstream

It is used to create files, write information to files, and read information from files.

ifstream

It is used to read information from files.

ofstream

It is used to create files and write information to the files.


C++ FileStream: writing to 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();

}

Output:

Check the output on file path text file: C:\TurboC++\Disk\TurboC3\BIN

5

lily

1000

C++ 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();

}

output



C++ Read and Write 

#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();

}

Output:



C++ Append

#include<iostream.h>

#include<fstream.h>

#include<conio.h>

void main()

{

 

    char str[50] = "Welcome to Program techie!";

    char ch;

    fstream fstream_ob;

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

    fstream_ob<< str << "\n";

    fstream_ob.close();

    getch();

}

Check the output on file path text file: C:\TurboC++\Disk\TurboC3\BIN

Output

Welcome to Program techie!

0 comments:

Post a Comment