0% found this document useful (0 votes)
17 views59 pages

Lec13 (Topic 8 File Handling)

Uploaded by

Abc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views59 pages

Lec13 (Topic 8 File Handling)

Uploaded by

Abc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 59

LECTURE 13

File Handling
Overview
13.1 Concept of a File
Files and Streams
13.2 Standard File Handling Functions
13.3 Binary Files
13.4 Random Access Files
13.1
Concept of a File
Files and Streams
I/O Streams
• I/O refers to program input and output
• Input is delivered to your program via a stream object
• Input can be from
• The keyboard
• A file
• Output is delivered to the output device via a stream
object
• Output can be to
• The screen
• A file
Streams and Basic File I/O
• Files for I/O are the same type of files used to
store programs
• A stream is a flow of data.
• Input stream: Data flows into the program
• If input stream flows from keyboard, the program will
accept data from the keyboard
• If input stream flows from a file, the program will accept
data from the file
• Output stream: Data flows out of the program
• To the screen
• To a file
cin And cout Streams
• cin
• Input stream connected to the keyboard
• cout
• Output stream connected to the screen
• cin and cout defined in the iostream library
• Use include directive: #include <iostream>

• You can declare your own streams to use with


files.
Why Use Files?
• Files allow you to store data permanently!
• Data output to a file lasts after the program ends
• An input file can be used over and over
• No typing of data again and again for testing
• Create a data file or read an output file at your
convenience
• Files allow you to deal with larger data sets
File I/O
• Reading from a file
• Taking input from a file
• Done from beginning to the end
• No backing up to read something again
• Just as done from the keyboard
• Writing to a file
• Sending output to a file
• Done from beginning to end
• No backing up to write something again
• Just as done to the screen
Stream Variables
• Like other variables, a stream variable…
• Must be declared before it can be used
• Must be initialized before it contains valid data
• Initializing a stream means connecting it to a file
• The value of the stream variable can be thought of as the file it is
connected to
• Can have its value changed
• Changing a stream value means disconnecting from one file and
connecting to another
Streams and Assignment

• A stream is a special kind of variable called an object


• Objects can use special functions to complete tasks

• Streams use special functions instead of the assignment


operator to change values
Declaring An
Input-file Stream Variable

• Input-file streams are of type ifstream

• Type ifstream is defined in the fstream library


• You must use the include and using directives
#include <fstream>
using namespace std;

• Declare an input-file stream variable using


ifstream in_stream;
Declaring An
Output-file Stream Variable

• Ouput-file streams of are type ofstream


• Type ofstream is defined in the fstream library
• You must use these include and using directives
#include <fstream>
using namespace std;

• Declare an input-file stream variable using


ofstream out_stream;
Connecting To A File
• Once a stream variable is declared, connect it to a file
• Connecting a stream to a file is opening the file
• Use the open function of the stream object


in_stream.open("infile.dat");

Double quotes
Period

File name on the disk


Using The Input Stream

• Once connected to a file, the input-stream variable can be


used to produce input just as you would use cin with the
extraction operator
• Example:
int one_number, another_number;
in_stream >> one_number
>> another_number;
Using The Output Stream
• An output-stream works similarly to the input-stream
• ofstream out_stream;
out_stream.open("outfile.dat");

out_stream << "one number = "


<< one_number
<< "another number = "
<< another_number;
External File Names
• An External File Name…
• Is the name for a file that the operating system uses
• infile.dat and outfile.dat used in the previous examples
• Is the "real", on-the-disk, name for a file
• Needs to match the naming conventions on your
system
• Usually only used in the stream's open statement
• Once open, referred to using the name of the stream
connected to it.
Closing a File
• After using a file, it should be closed
• This disconnects the stream from the file
• Close files to reduce the chance of a file being
corrupted if the program terminates abnormally
• It is important to close an output file if your program later
needs to read input from the output file
• The system will automatically close files if you forget as
long as your program ends normally
Slide 6-
18
Objects
• An object is a variable that has functions and data
associated with it
• in_stream and out_stream each have a function named open
associated with them
• in_stream and out_stream use different versions of a function
named open
• One version of open is for input files
• A different version of open is for output files
Member Functions
• A member function is a function associated with an object
• The open function is a member function of in_stream in the
previous examples
• A different open function is a member function of out_stream in the
previous examples
Classes
• A type whose variables are objects, is a class
• ifstream is the type of the in_stream variable (object)
• ifstream is a class
• The class of an object determines its member functions
• Example:
ifstream in_stream1, in_stream2;
• in_stream1.open and in_stream2.open are the same
function but might have different arguments
Calling a Member Function
• Calling a member function requires specifying the
object containing the function
• The calling object is separated from the member
function by the dot operator
• Example: in_stream.open("infile.dat");

Calling object Member function

Dot operator
Errors On Opening Files
• Opening a file could fail for several reasons
• Common reasons for open to fail include
• The file might not exist
• The name might be typed incorrectly

• May be no error message if the call to open fails


• Program execution continues!
Catching Stream Errors

• Member function fail, can be used to test the


success of a stream operation
• fail returns a boolean type (true or false)
• fail returns true if the stream operation failed
Halting Execution
• When a stream open function fails, it is generally best to
stop the program
• The function exit, halts a program
• exit returns its argument to the operating system
• exit causes program execution to stop
• exit is NOT a member function
• Exit requires the include and using directives
#include <cstdlib>
using namespace std;
Using fail and exit
• Immediately following the call to open, check
that the operation was successful:

in_stream.open("stuff.dat");
if( in_stream.fail( ) )
{
cout << "Input file opening failed.\n";
exit(1) ;
}
Techniques for File I/O
• When reading input from a file…
• Do not include prompts or echo the input
• The lines cout << "Enter the number: ";
cin >> the_number;
cout << "The number you entered is "
<< the_number;
become just one line

in_file >> the_number;

• The input file must contain exactly the data expected


Appending Data (optional)
• Output examples so far create new files
• If the output file already contains data, that data
is lost
• To append new output to the end an existing file
• use the constant ios::app defined in the iostream
library:
outStream.open("important.txt", ios::app);

• If the file does not exist, a new file will be created


Slide 6-
29
File Names as Input (optional)
• Program users can enter the name of a file to use for
input or for output
• Program must use a variable that can hold multiple
characters
• A sequence of characters is called a string
• Declaring a variable to hold a string of characters:
char file_name[16];
• file_name is the name of a variable
• Brackets enclose the maximum number of characters + 1
• The variable file_name contains up to 15 characters
Using A Character String
• char file_name[16];
cout << "Enter the file_name ";
cin >> file_name;
ifstream in_stream;
in_stream.open(file_name);
if (in_stream.fail( ) )
{
cout << "Input file opening failed.\n";
exit(1);
}
The End of The File
• Input files used by a program may vary in length
• Programs may not be able to assume the number
of items in the file
• A way to know the end of the file is reached:
• The boolean expression (in_stream >> next)
• Reads a value from in_stream and stores it in next
• True if a value can be read and stored in next
• False if there is not a value to be read (the end of the file)

Slide 6- 32
End of File Example
• To calculate the average of the numbers in a file
• double next, sum = 0;
int count = 0;
while(in_stream >> next)
{
sum = sum + next;
count++;
}

double average = sum / count;

Slide 6- 33
13.2
Standard File Handling Functions
Step 1
• Include the proper directory to use all the file stream
member methods.

#include <fstream>
Step 2
• Create a file instance
• For reading from files
• ifstream myfile;
• For writing to files
• ofstream myfile;

• Simplest is a combination of read/write


• fstream myfile;
Step 3
• Associate the file instance with an actual file
• There are 2 ways for this:
1) Using the constructor
fstream myfile("tmp.txt", ios::out);
2) Using the open() member method
fstream myfile;
myfile.open("tmp.txt", ios::out);

• The 2 parameters are


1) file name
2) file access mode
• File access modes

ios::in Open for input operations.


ios::out Open for output operations.
ios::binary Open in binary mode.
Set the initial position at the end of the file.
ios::ate
If this flag is not set, the initial position is the beginning of the file.
All output operations are performed at the end of the file, appending the
ios::app
content to the current content of the file.
If the file is opened for output operations and it already existed, its
ios::trunc
previous content is deleted and replaced by the new one.

• Multiple access modes can be combine using bitwise OR


• fstream myfile("tmp.txt", ios::out | ios::binary);
Step 4
• Test if file is properly opened
• There are various ways to accomplish this
• Below are a few samples:

fstream myfile("tmp.txt", ios::in | ios::binary);


if(myfile.is_open()){
cout << "Success\n";
//perform operations needed
}
else
exit(1);
fstream myfile("tmp.txt", ios::in | ios::binary);
if(myfile.good()){
cout << "Success\n";
//perform operations needed
}

else
exit(1);
fstream myfile("tmp.txt", ios::in | ios::binary);
if(myfile){
cout << "Success\n";
//perform operations needed
}

else
exit(1);
Step 5
• Writing to a file
1) Using the insertion operator <<
myfile << "Hello world!\nHow are we
today?\n";
2) Using the put() method

char ch;
cout << "Type some text (type a dot to finish):\n";
while((ch = cin.get())
&& (ch!='.')
&& (myfile.put(ch)))
{}
Step 6
• Reading from a file
1) Using the extraction operator >>
string tmp;
while(!myfile.eof()){
myfile >> tmp;
if(myfile.good())
cout << tmp << " ";
}
endl(cout);
2) Using the get() method
char tmp;
while(myfile.good()){
tmp = myfile.get();
if(myfile.good())
cout << tmp;
}
3) Using the getline() method – string version
string tmp;
while(myfile.good()){
getline(myfile, tmp);
if(myfile.good())
cout << tmp << endl;
}
Step 7
• Closing a file
int main () {
fstream myfile("tmp.txt", ios::out);
myfile << "sample test string";
myfile.close();

myfile.open("tmp.txt", ios::in);
string tmp;
getline(myfile, tmp);
cout << tmp << endl;
myfile.close();

return 0;
}
13.3
Binary Files
Binary
• Data written into a binary files are not so easily readable.
• Access to a binary file deals with memory blocks.
• Therefore, it’s easier to manipulate especially when
having more complex data structures like classes and/or
arrays.
Writing to a binary file
struct info{
char name[10];
int age;
};

int main () {
info ary[2] = { {"howdy", 19},
{"nitey", 12} };

cout << sizeof(ary) << endl;


cout << sizeof(info)*2 << endl;

fstream myfile("tmp.txt", ios::out | ios::binary);


myfile.write((char *) ary, sizeof(ary));

return 0;
}
Reading from a binary file
• Editing from the previous program…

info dest[2];
myfile.open("tmp.txt", ios::in | ios::binary);
myfile.read((char*) dest, sizeof(dest));

for(int i=0; i<2; i++)


cout << dest[i].name << " "
<< dest[i].age << endl;
13.4
Random Access Files
Stream position
• Return a value of the member type streampos, which is a
type representing
• the current get position (in the case of tellg) or - reading from file
• the put position (in the case of tellp) - writing to file

• allow to change the location of the get and put positions


• seekg()
• seekp()
• seekg ( position );
seekp ( position );

Using this prototype, the stream pointer is changed to the


absolute position (counting from the beginning of the file).
The type for this parameter is streampos, which is the
same type as returned by functions tellg and tellp.
• seekg ( offset, direction );
seekp ( offset, direction );

• Using this prototype, the get or put position is set to an


offset value relative to some specific point determined by
the parameter direction.
• direction can take any of the following values:

ios::beg offset counted from the beginning of the stream


ios::cur offset counted from the current position
ios::end offset counted from the end of the stream
struct info{
char name[7];
};

int main () {
info source[3] = {"senior", "middle", "junior"};

ofstream outfile("test.txt", ios::binary);


outfile.write((char*)source, sizeof(source));
outfile.close();

ifstream infile("test.txt", ios::binary);


infile.seekg(sizeof(info));
info *ptr = new info;
infile.read((char*)ptr, sizeof(info));
cout << ptr ->name<< endl; //cout "middle"

return 0;
}
Knowledge Check
• Can you

• Find the size of a file using tellg and seekg


(try and figure it out before looking at the answer in the next slide)
int main () {
streampos begin,end;
ifstream myfile ("test.txt", ios::binary);
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "size is: " << (end-begin) << " bytes.\n";
return 0;
}
The End

You might also like