File i o in c ii
This presentation is the property of its rightful owner.
Sponsored Links
1 / 9

File I/O in C ++ II PowerPoint PPT Presentation


  • 80 Views
  • Uploaded on
  • Presentation posted in: General

File I/O in C ++ II. Open() function. The name of file. Open() is a member function in each classes ( fstream , ifstream , ofstream ) Void fstream :: open ( const char *filename, openmode mode); Void ifstream ::open ( const char * filename, openmode mode= ios :: in);

Download Presentation

File I/O in C ++ II

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


File i o in c ii

File I/O in C++ II


Open function

Open() function

The name of file

  • Open() is a member function in each classes ( fstream, ifstream, ofstream)

  • Voidfstream:: open ( const char *filename, openmodemode);

  • Voidifstream::open ( const char *filename, openmodemode= ios:: in);

  • Voidofstream:: open ( const char *filename, openmodemode=

    • ios:: out |iso :: trunc);

Optiional to determine how the file is opened

You can combine 2 or more of these value by ORing them together


File open mode

File Open Mode


File open mode1

File Open Mode

#include <fstream>

using namespace std;

void main()

{

ofstreamoutFile("file1.txt", ios::out);

outFile << "That's new!\n";

outFile.close();

}

If you want to set more than one open mode, just use the OR operator- |. This way:

ios::ate | ios::binary


File format

File format

  • In c++ files we (read from/ write to) them as a stream of characters

  • What if I want to write or read numbers ?


Example writing to file

Example writing to file

#include <iostream>

#include <fstream>

using namespace std;

void main()

{

ofstreamoutFile;

// open an exist file fout.txt

outFile.open("number.txt",ios::app);

if (!outFile.is_open())

{ cout << " problem with opening the file ";}

else

{outFile<<200 <<endl ;

cout << "done writing" <<endl;}

outFile.close();

}


Example reading from file

Example Reading from file

#include <iostream>

#include <fstream>

#include <string>

#include <sstream>

using namespace std;

void main()

{//Declare and open a text file

ifstreamINFile("number.txt");

string line;

inttotal=0;

while(! INFile.eof())

{//fetch line from number.txt and put it in a string

getline(INFile, line);

//converting line string to int

stringstream(line) >> total;

cout << line <<endl;

cout <<total +1<<endl;}

INFile.close(); // close the file

}


  • Login