file i/o in c++. using input/output files a computer file is stored on a secondary storage device...

25
FILE I/O IN C++

Upload: horace-phillips

Post on 14-Jan-2016

219 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 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

FILE I/O IN C++

Page 2: 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

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;

must be opened before it is used.

Page 3: 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

General File I/O Steps

1. Include the header file fstream in the program.

2. Declare file stream variables.

3. Associate the file stream variables with the input/output sources.

4. Open the file

5. Use the file stream variables with >>, <<, or other input/output functions.

6. Close the files.

Page 4: 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

Using Input/Output Files

stream - a sequence of characters interactive (iostream)

cin - input stream associated with keyboard.· cout - output stream associated with display

file (fstream) ifstream - defines new input stream (normally

associated with a file).

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

Page 5: 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

Stream I/O Library Header Files

Note: There is no “.h” on standard header files : <fstream>

iostream -- contains basic information required for all stream I/O operations

iomanip -- contains information useful for performing formatted I/O with parameterized stream manipulators

fstream -- contains information for performing file I/O operations

strstream -- contains information for performing in-memory I/O operations (i.e., into or from strings in memory)

Page 6: 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

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

Classes for Stream I/O in C++

Page 7: 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

C++ streams

//Add additional header files you use

#include <fstream>int main (){ /* Declare file stream variables such as

the following */

ifstream fsIn; //inputofstream fsOut; // outputfstream both //input & output

//Open the files

inData.open("prog.dat"); //open the input file

outData.open("prog.out"); //open the output file

//Code for data manipulation

.

.

//Close files

inData.close();

outData.close();

return 0; }

Page 8: 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

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 9: 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

Object and Member Functions

input_stream.open("numbers.dat“)

Stream handle

Name

Calling

Object

Dot

Operator

Member Function

Name

File Name

Dir:\\folder\fileName.extention

Extention ( .dat, .out, .txt)

Page 10: 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

Open()

Opening a file associates a file stream variable declared in the program with a physical file at the source, such as a disk.

In the case of an input file: the file must exist before the open statement executes. If the file does not exist, the open statement fails and the

input stream enters the fail state An output file does not have to exist before it is

opened; if the output file does not exist, the computer prepares an

empty file for output. If the designated output file already exists, by default, the

old contents are erased when the file is opened.

Page 11: 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

Validate the file before trying to access

By checking the stream variable;

If ( ! Mystream) {Cout << “Cannot open file.\n ”;

}

By using bool is_open() function.

If ( ! Mystream.is_open()) {Cout << “File is not open.\n ”;

}

First method Second method

Page 12: 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

File I/O Example: Open the file with validation

#include <fstream>

using namespace std;

int main()

{

/* declear and automaticaly open the file*/

ofstream outFile(“fout.txt");

// Open validation

if(! outFile) {Cout << “Cannot open file.\n ”;return 1;

}return 0;

}

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

// declear output file variableofstream outFile;// open an exist file fout.txt

outFile.open(“fout.txt”);// Open validation

if(! outFile.is_open() ) {Cout << “Cannot open file.\n ”;

return 1;

}

return 0;}

First Method (use the constructor)

Second Method ( use Open function)

Page 13: 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

File I/O Example: Writing

#include <fstream>using namespace std;int main(){ /* declear and automaticaly open the

file*/ofstream outFile(“fout.txt");

//behave just like cout, put the word into the fileoutFile << "Hello World!";

outFile.close();

return 0;}

#include <fstream>using namespace std;int main(){ // declear output file variable

ofstream outFile;// open an exist file fout.txt

outFile.open(“fout.txt”);

//behave just like cout, put the word into the fileoutFile << "Hello World!";

outFile.close();

return 0;}

First Method (use the constructor)

Second Method ( use Open function)

Page 14: 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

File I/O Example: Reading

#include <iostream>#include <fstream>

int main(){ //Declare and open a text file

ifstream openFile(“data.txt"); char ch;

//do until the end of filewhile( ! OpenFile.eof() ){

OpenFile.get(ch); // get one charactercout << ch; // display the

character}OpenFile.close(); // close the file

return 0;}

#include <iostream>

#include <fstream>

#include <string>

int main()

{ //Declare and open a text file

ifstream openFile(“data.txt");

string line;

while(!openFile.eof())

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

getline(openFile, line);

cout << line;

}

openFile.close(); // close the file

return 0; }

Read char by char Read a line

Page 15: 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

More Input File-Related Functions

ifstream fsin; fsIn.open(const char[] fname)

connects stream fsIn to the external file fname. fsIn.get(char& character)

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

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

Page 16: 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

More Output File-Related Functions

ofstream fsOut; fsOut.open(const char[] fname)

connects stream fsOut to the external file fname. fsOut.put(char character)

inserts character character to the output stream fsOut.

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

Page 17: 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

File Open ModeName Description

ios::in Open file to read

ios::out Open file to write

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

ios::ate All the date 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 18: 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

File 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

Page 19: 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

Dealing with Binary files

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

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

read(): block reading

write(): block writing

Page 20: 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

Dealing with Binary files

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

seekp():Go to a specific position when writing

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

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

Page 21: 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

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

}

Page 22: 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

Binary File I/O Examples

//Example 2: Using read() and write()

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

fstream File("test_file.txt",ios::out | ios::in | ios::binary);char arr[13];strcpy(arr,"Hello World!"); //put Hello World! into the array

File.write(arr,5); //put the first 5 symbols into the file- "Hello"

File.seekg(ios::beg); //go to the beginning of the file

static char read_array[10]; //I will put the read data, here

File.read(read_array,3); //read the first 3 symbols- "Hel"

cout << read_array << endl; //display them

File.close();}

Page 23: 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

More 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 long

cout << File.tellg() << endl; File.close();

}

Page 24: 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

Summary of InputFile-Related Functions #include <fstream>

ifstream fsIn; fsIn.open(const char[] fname)

connects stream fsIn to the external file fname. fsIn.get(char& c)

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

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

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

fsIn >> c; //Behaves just like cin

Page 25: 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

Summary of OutputFile-Related Functions #include <fstream>

ofstream fsOut; fsOut.open(const char[] fname)

connects stream fsOut to the external file fname. fsOut.put(char c)

inserts character c to the output stream fsOut. fsOut.eof()

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

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