file i/o in c++

Post on 19-Mar-2016

217 Views

Category:

Documents

30 Downloads

Preview:

Click to see full reader

DESCRIPTION

File I/O in C++. Using Input/Output Files. A computer file is stored on a secondary storage device (e.g., disk); is permanent; can be used to provide input data to a program or receive output data from a program, or both; should reside in Project directory for easy access; - PowerPoint PPT Presentation

TRANSCRIPT

File I/O in C++File I/O in C++

Using Input/Output FilesUsing Input/Output Files A computer fileA computer file

• is stored on a secondary storage device is stored on a secondary storage device (e.g., disk);(e.g., disk);

• is permanent;is permanent;• can be used to provide input data to a can be used to provide input data to a

program or receive output data from a program or receive output data from a program, or both;program, or both;

• should reside in Project directory for easy should reside in Project directory for easy access;access;

• must be opened before it is used.must be opened before it is used.

General File I/O StepsGeneral File I/O Steps

• Declare a file name variable

• Associate the file name variable with the disk file name

• Open the file

• Use the file

• Close the file

Using Input/Output FilesUsing Input/Output Files streamstream - a sequence of characters - a sequence of characters

• interactive (iostream)interactive (iostream) cincin - input stream associated with - input stream associated with keyboard.keyboard. coutcout - output stream associated with - output stream associated with display.display.

• file (fstream)file (fstream) ifstreamifstream - defines new input stream (normally - defines new input stream (normally

associated with a file).associated with a file). ofstreamofstream - defines new output stream (normally - defines new output stream (normally

associated with a file).associated with a file).

Stream I/O Library Header FilesStream I/O Library Header Files Note: There is no “.h” on standard header files : <fstream>Note: There is no “.h” on standard header files : <fstream> iostream -- contains basic information required for all iostream -- contains basic information required for all

stream I/O operationsstream I/O operations iomanip -- contains information useful for performing iomanip -- contains information useful for performing

formatted I/O with parameterized stream manipulatorsformatted I/O with parameterized stream manipulators fstream -- contains information for performing file I/O fstream -- contains information for performing file I/O

operationsoperations strstream -- contains information for performing in-memory strstream -- contains information for performing in-memory

I/O operations (i.e., into or from strings in memory)I/O operations (i.e., into or from strings in memory)

ios is the base class.ios is the base class. istream and ostream inherit from iosistream and ostream inherit from ios ifstream inherits from istream (and ios)ifstream inherits from istream (and ios) ofstream inherits from ostream (and ios)ofstream inherits from ostream (and ios) iostream inherits from istream and ostream (& ios)iostream inherits from istream and ostream (& ios) fstream inherits from ifstream, iostream, and ofstream fstream inherits from ifstream, iostream, and ofstream

Classes for Stream I/O in C++Classes for Stream I/O in C++

C++ streams

#include <fstream>#include <fstream>int main (void)int main (void){{ //Local declarations//Local declarations ifstream fsIn;ifstream fsIn; ofstream fsOut;ofstream fsOut; .. .. .. return 0;return 0;}}

input_stream.open("numbers.dat")input_stream.open("numbers.dat")

Stream handleName

CallingObject

DotOperator

Member Function Name

File Name

Object and Member FunctionsObject and Member Functions

File I/O Example: WritingFile I/O Example: Writing

#include <fstream>#include <fstream>using namespace std;using namespace std;int main(void)int main(void){{

ofstream outFile(“fout.txt");ofstream outFile(“fout.txt");outFile << "Hello World!";outFile << "Hello World!";outFile.close();outFile.close();return 0;return 0;

}}

File I/O Example: WritingFile I/O Example: Writing#include <fstream>#include <fstream>using namespace std;using namespace std;

int main(void)int main(void){{

ofstream outFile;ofstream outFile; outFile.open(“fout.txt”);outFile.open(“fout.txt”);

outFile << “First line”; //behave just like coutoutFile << “First line”; //behave just like coutoutFile.close();outFile.close();

outFile<<“Another line”<<endl; //??outFile<<“Another line”<<endl; //??return 0;return 0;

}}

File I/O Example: ReadingFile I/O Example: Reading#include <iostream>#include <iostream>#include <fstream>#include <fstream>

int main(void)int main(void){{

ifstream openFile(“data.txt"); //open a text file data.txtifstream openFile(“data.txt"); //open a text file data.txtchar ch;char ch;while(!OpenFile.eof())while(!OpenFile.eof()){{OpenFile.get(ch);OpenFile.get(ch);cout << ch;cout << ch;}}OpenFile.close();OpenFile.close();

return 0;return 0;}}

File I/O Example: ReadingFile I/O Example: Reading#include <iostream>#include <iostream>#include <fstream>#include <fstream>#include <string>#include <string>

int main(void)int main(void){{

ifstream openFile(“data.txt"); //Declare and open a text fileifstream openFile(“data.txt"); //Declare and open a text filestring line;string line;

while(!openFile.eof())while(!openFile.eof()){{getline(openFile,line);//fetch line from data.txt and put it in a stringgetline(openFile,line);//fetch line from data.txt and put it in a stringcout << line;cout << line;}}openFile.close();openFile.close();

return 0;return 0;}}

File I/O Example: ReadingFile I/O Example: Reading#include <iostream>#include <iostream>#include <fstream>#include <fstream>#include <string>#include <string>

int main(void)int main(void){{

ifstream openFile(“data.txt"); //open a text file data.txtifstream openFile(“data.txt"); //open a text file data.txtstring line;string line;

if(openFile.is_open()){ //if(openFile.is_open()){ //while(!openFile.eof()){while(!openFile.eof()){getline(openFile,line);//read a line from data.txt and put it in a stringgetline(openFile,line);//read a line from data.txt and put it in a stringcout << line;cout << line;}}

else{else{ cout<<“File does not exist!”<<endl;cout<<“File does not exist!”<<endl; exit(1);}exit(1);} }}

openFile.close();openFile.close(); return 0;return 0;}}

More Input File-Related FunctionsMore Input File-Related Functions

ifstream fsin;ifstream fsin; fsIn.open(fsIn.open(constconst charchar[] fname)[] fname)

• connects stream connects stream fsInfsIn to the external file to the external file fname.fname. fsIn.get(fsIn.get(charchar& character)& character)

• extracts next character from the input stream extracts next character from the input stream fsInfsIn and places it in the character variable and places it in the character variable character.character.

fsIn.eof()fsIn.eof()• tests for the end-of-file condition.tests for the end-of-file condition.

More Output File-Related FunctionsMore Output File-Related Functions

ofstream fsOut;ofstream fsOut; fsOut.open(fsOut.open(constconst charchar[] fname)[] fname)

• connects stream connects stream fsOutfsOut to the external file to the external file fname.fname.

fsOut.put(fsOut.put(charchar character) character)• inserts character inserts character charactercharacter to the output to the output

stream stream fsOutfsOut.. fsOut.eof()fsOut.eof()

• tests for the end-of-file condition.tests for the end-of-file condition.

File Open ModeFile Open ModeName Description

ios::in Open file to readios::out Open file to writeios::app All the date you write, is put at the end of the file.

It calls ios::outios::ate All the date you write, is put at the end of the file.

It does not call ios::outios::trunc Deletes all previous content in the file. (empties

the file)ios::nocreate If the file does not exist, 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.

File Open ModeFile Open Mode#include <fstream>int main(void){

ofstream outFile("file1.txt", ios::out);outFile << "That's new!\n";outFile.close();

Return 0;}

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

Dealing with Binary filesDealing with Binary files

Functions for binary file handlingFunctions for binary file handling get(): get(): read a byte and point to the next byte to readread a byte and point to the next byte to read

put(): put(): write a byte and point to the next location for writewrite a byte and point to the next location for write

read(): read(): block readingblock reading

write(): write(): block writingblock writing

Dealing with Binary filesDealing with Binary files

Some useful functionsSome useful functions seekg():seekg():Go to a specific position when readingGo to a specific position when reading

seekp():seekp():Go to a specific position when writingGo to a specific position when writing

tellg()tellg(): : Retunrs an int type, that shows the current position of Retunrs an int type, that shows the current position of the inside-pointer. This one works only when you read a file.the inside-pointer. This one works only when you read a file.

tellp():tellp(): The same as tellg() but used when we write in a file.The same as tellg() but used when we write in a file. flush():flush():Save data from the buffer to the output file.Save data from the buffer to the output file.

Binary File I/O ExamplesBinary File I/O Examples

//Example 1: Using get() and put()#include <iostream>#include <fstream>void main(){

fstream File("test_file",ios::out | ios::in | ios::binary);char ch;ch='o';File.put(ch); //put the content of ch to the fileFile.seekg(ios::beg); //go to the beginning of the fileFile.get(ch); //read one charactercout << ch << endl; //display itFile.close();

}

Binary File I/O ExamplesBinary File I/O Examples//Example 2: Using read() and write()//Example 2: Using read() and write()

#include <fstream.h>#include <fstream.h>#include <string.h>#include <string.h>void main()void main(){{

fstream File("test_file.txt",ios::out | ios::in | ios::binary);fstream File("test_file.txt",ios::out | ios::in | ios::binary);char arr[13];char arr[13];strcpy(arr,"Hello World!"); strcpy(arr,"Hello World!"); //put Hello World! into the array//put Hello World! into the arrayFile.write(arr,5); File.write(arr,5); //put the first 5 symbols into the file- "Hello"//put the first 5 symbols into the file- "Hello"File.seekg(ios::beg); File.seekg(ios::beg); //go to the beginning of the file//go to the beginning of the filestatic char read_array[10]; static char read_array[10]; //I will put the read data, here//I will put the read data, hereFile.read(read_array,3); File.read(read_array,3); //read the first 3 symbols- "Hel"//read the first 3 symbols- "Hel"cout << read_array << endl; cout << read_array << endl; //display them//display themFile.close();File.close();

}}

More Binary File I/O ExamplesMore Binary File I/O Examples#include <fstream>void main(){

//if we have "Hello" in test_file.txtifstream File("test_file.txt");char arr[10];File.read(arr,10);

//this should return 5, as Hello is 5 characters longcout << File.tellg() << endl; File.close();

}

Summary of InputSummary of InputFile-Related FunctionsFile-Related Functions

#include#include <fstream> <fstream>ifstream fsIn;ifstream fsIn; fsIn.open(fsIn.open(constconst charchar[] fname)[] fname)

• connects streamconnects stream fsInfsIn to the external fileto the external file fname.fname. fsIn.get(fsIn.get(charchar& c)& c)

• extracts next character from the input stream extracts next character from the input stream fsInfsIn and and places it in the character variable places it in the character variable c.c.

fsIn.eof()fsIn.eof()• tests for the end-of-file condition.tests for the end-of-file condition.

fsIn.close()fsIn.close()• disconnects the stream and associated file.disconnects the stream and associated file.

fsIn >> c; fsIn >> c; //Behaves just like cin//Behaves just like cin

Summary of OutputSummary of OutputFile-Related FunctionsFile-Related Functions

#include#include <fstream> <fstream>ofstream fsOut;ofstream fsOut; fsOut.open(fsOut.open(constconst charchar[] fname)[] fname)

• connects streamconnects stream fsOutfsOut to the external fileto the external file fname.fname. fsOut.put(fsOut.put(charchar c) c)

• inserts character inserts character cc to the output stream to the output stream fsOutfsOut.. fsOut.eof()fsOut.eof()

• tests for the end-of-file condition.tests for the end-of-file condition. fsOut.close()fsOut.close()

• disconnects the stream and associated file.disconnects the stream and associated file. fsOut << c;fsOut << c; //Behaves just like cout//Behaves just like cout

top related