file i/o in c ++ ii

9
File I/O in C++ II

Upload: olaf

Post on 05-Jan-2016

25 views

Category:

Documents


0 download

DESCRIPTION

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); - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: File I/O in C ++  II

File I/O in C++ II

Page 2: File I/O in C ++  II

Open() function• 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);

• Void ofstream :: open ( const char *filename, openmode mode= ▫ ios:: out | iso :: trunc);

The name of file

Optiional to determine how the file is opened

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

together

Page 3: File I/O in C ++  II

File Open ModeName Description

ios::in Open file to read

ios::out Open file to write

ios::app All the data you write, is put at the end of the file. It calls ios::out

ios::ate All the data you write, is put at the end of the file. It does not call ios::out

ios::trunc Deletes all previous content in the file. (empties the file)

ios::nocreate If the file does not exists, opening it with the open() function gets impossible.

ios::noreplace If the file exists, trying to open it with the open() function, returns an error.

ios::binary Opens the file in binary mode.

Page 4: File I/O in C ++  II

File Open Mode#include <fstream>using namespace std;void main(){ofstream outFile("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

Page 5: File I/O in C ++  II

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 ?

Page 6: File I/O in C ++  II

Example writing to file #include <iostream>#include <fstream>using namespace std;void main(){ofstream outFile;// 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();

}

Page 7: File I/O in C ++  II
Page 8: File I/O in C ++  II

Example Reading from file #include <iostream>#include <fstream>#include <string>

#include <sstream>using namespace std;void main(){//Declare and open a text fileifstream INFile("number.txt"); string line;int total=0;while(! INFile.eof()){//fetch line from number.txt and put it in a stringgetline(INFile, line);//converting line string to int

stringstream(line) >> total;

cout << line <<endl;cout <<total +1<<endl;}

INFile.close(); // close the file }

Page 9: File I/O in C ++  II