Programming Principles II Lecture Notes 7 Files Andreas Savva.
Post on 03-Jan-2016
220 Views
Preview:
Transcript
Programming Programming Principles IIPrinciples II
Lecture Notes 7Lecture Notes 7FilesFiles
Andreas Savva
22
FilesFiles A A filefile is a group of organized data stored in is a group of organized data stored in
secondary storage.secondary storage. Every file has a Every file has a filenamefilename – the name by which the – the name by which the
operating system refers to the contents of the file.operating system refers to the contents of the file.
Dear AnnI am now living in Cyprus where Igot married and bought a house.This is a great place to be. The weather is perfect and life is . . .
Letter.txt
33
Type of FilesType of Files The operating system usually distinguishes files in The operating system usually distinguishes files in
different categories:different categories: Text file (contains ASCII characters)Text file (contains ASCII characters) Executable (Contains code of a program)Executable (Contains code of a program) Binary file (contains arbitrary data)Binary file (contains arbitrary data)
Application programs usually store data in binary Application programs usually store data in binary files in a format understood only by the specific files in a format understood only by the specific application program e.g.application program e.g. MS Word documents (.doc)MS Word documents (.doc) MS Excel files (.xls)MS Excel files (.xls) GIF image files (.gif)GIF image files (.gif)
44
File Handle in C++File Handle in C++ In order to be able to handle a file we need to:In order to be able to handle a file we need to:
include the library include the library fstreamfstream.. declare an object to represent a file which will permit declare an object to represent a file which will permit
reading, writing, etc.reading, writing, etc. C++ provides the following classes to perform input C++ provides the following classes to perform input
and output from/to files:and output from/to files: ofstreamofstream: stream class to write in files: stream class to write in files ifstreamifstream: Stream class to read from files: Stream class to read from files fstreamfstream: Stream class to read and write from/to files: Stream class to read and write from/to files
#include <iostream>#include <fstream>using namespace std;int main() { fstream myFile; . . . return 0;}
55
Opening a FileOpening a File To open a file we must:To open a file we must:
determine the file name (e.g. data.txt)determine the file name (e.g. data.txt) create a new file handle (e.g. myFile)create a new file handle (e.g. myFile) use the handle to open the file use the handle to open the file myFile.open(filename, mode)myFile.open(filename, mode)
To open an existing file to read from, the To open an existing file to read from, the modemode must must be be ios::inios::in..
#include <iostream>#include <fstream>using namespace std;int main() {
fstream myFile;myFile.open(”data.txt”,ios::in);
. . . return 0;}
66
Using Using fstreamfstream Objects Objects In using both In using both ifstreamifstream and and ofstreamofstream objects the objects the
mode, input or output, is implied by the object. Thus,mode, input or output, is implied by the object. Thus, ifstreamifstream objects can only be used for input objects can only be used for input ofstreamofstream objects can only be used for output objects can only be used for output fstreamfstream objects can be used for input or output but require objects can be used for input or output but require
an explicit mode designation.an explicit mode designation.
#include <iostream>#include <fstream>using namespace std;int main() {
ifstream inFile;ofstream outFile;fstream addFile;inFile.open(”in.txt”,ios::in);outFile.open(”out.txt”,ios::out);addFile.open(”new.txt”,ios::app);
. . .return 0;
}
77
Opening a File ModeOpening a File Mode Mode is an optional parameter with a combination of the following flags:Mode is an optional parameter with a combination of the following flags:
fstream myFile;fstream myFile;myFile.open(”example.bin”, ios::out | ios::app | myFile.open(”example.bin”, ios::out | ios::app |
ios::bin);ios::bin);
Mode Description
ios::in Open a text file in input mode
ios::out Open a text file in output mode
ios::app Open a text file in append mode
ios::ate Go to the end of the open file
ios::binary Open a binary file in input mode (default is text file)
ios::trunc Delete file contents if file exists
All these flags can be combined using the bitwise operator OR (All these flags can be combined using the bitwise operator OR (||). For ). For example, the following will open a the file example, the following will open a the file example.binexample.bin in in binarybinary mode mode to to addadd data: data:
88
Default ModesDefault Modes Each one of the Each one of the open() open() member functions of the classes member functions of the classes
ofstreamofstream, , ifstreamifstream and and fstreamfstream has a default mode that is has a default mode that is used if the file is opened without a second argument, i.e.used if the file is opened without a second argument, i.e.
Class Default mode parameter
ofstream
ios::out
ifstream ios::in
fstream ios::in | ios::out The three classes have a constructor that takes the same The three classes have a constructor that takes the same
parameters as parameters as open() open() and automatically calls it. and automatically calls it.
ofstream myFile;ofstream myFile;myFile.open(”data.txt”);myFile.open(”data.txt”);
ofstream myFile(”data.txt”, ios::out);ofstream myFile(”data.txt”, ios::out);
99
Opening a FileOpening a File File streams opened in File streams opened in binary mode binary mode perform input and output perform input and output
operations independently of any format considerations.operations independently of any format considerations. Non-binary files are known as Non-binary files are known as text filestext files, and some translations , and some translations
may occur due to formatting of some special characters (like may occur due to formatting of some special characters (like newline and carriage return characters).newline and carriage return characters).
The method The method is_open() is_open() with no arguments (returns a with no arguments (returns a boolbool value) can be called to check whether or not a file stream has value) can be called to check whether or not a file stream has successfully opened a file.successfully opened a file.
ofstream myFile(”data.txt”);if (myFile.is_open()){
// ok, proceed with output }else cout << ”Unable to open file”;
1010
Reading from a Text-FileReading from a Text-File
#include <iostream>#include <fstream>using namespace std;
int main() { ifstream inFile(”data.txt”);
if (inFile.is_open()) { char ch; int k; char s[50];
inFile >> ch; inFile >> k >> s;
cout << k << s << ch; } return 0;}
3458 Jurassic Park
data.txt
458Jurassic3
34A58B Jurassic Park
data.txt
4A58B3
Ignores spaces and
control characters
Data output and input operations on text-files are performed Data output and input operations on text-files are performed in the same way as with in the same way as with coutcout and and cincin..
1111
Reading MethodsReading Methods There exist a variety of methods for reading There exist a variety of methods for reading
streams (files). streams (files). Read a single character, including spaces and control Read a single character, including spaces and control
characters:characters:
ch = myFile.get();ch = myFile.get(); Read a line of text or up to 20 characters into array s[] :Read a line of text or up to 20 characters into array s[] :
myFile.getline(s,20);myFile.getline(s,20); Read a line of text or up to 20 characters or until character Read a line of text or up to 20 characters or until character
’A’ occurred into array s[] :’A’ occurred into array s[] :
myFile.getline(s,20,’A’);myFile.getline(s,20,’A’); cincin is also a stream object; we can use the same is also a stream object; we can use the same
operations:operations:
ch = cin.get();ch = cin.get();
cin.getline(s,20);cin.getline(s,20);
cin.getline(s,20,’A’);cin.getline(s,20,’A’);
1212
Exceptions and ErrorsExceptions and Errors With file operations there may be a variety of With file operations there may be a variety of
problems, i.e.problems, i.e. File not found during opening.File not found during opening. File cannot be opened (already opened exclusively by File cannot be opened (already opened exclusively by
other program).other program). End of file reached.End of file reached. Disk full during writing.Disk full during writing.
Detecting when a problem occurred:Detecting when a problem occurred:
!myFile!myFilemyFile.fail()myFile.fail()
myFile.open("data.txt",ios::in);
if (!myFile) // an error has occurred
cout << ”Could not open file”;
. . .
1313
Checking State FlagsChecking State Flags A number of A number of boolbool member functions exist to check for member functions exist to check for
specific states of a stream:specific states of a stream:
Method Description
bad() Returns true if a reading or writing operation fails. For example, if there is an attempt to write in a file that was open for input, or if there is no available memory on the device that there is an attempt to write in a file.
fail() Returns true in the same cases as bad(), but also in the case that a format error happens. For example if a character is extracted while an integer is expected.
eof() Returns true if a file opened for input has reached the end.
good() It is the most generic state flag – it returns false in the same cases in which calling any of the previous functions would return true.
1414
Closing a FileClosing a File After completing the use of the file, it should be After completing the use of the file, it should be
closed so that it resources become available again.closed so that it resources become available again. Closing a file:Closing a file:
myFile.close();myFile.close(); Once closing the file, the file becomes available to Once closing the file, the file becomes available to
be opened by other processes and the stream be opened by other processes and the stream object can be used to open another file.object can be used to open another file.
In case that an object is destructed before is closed In case that an object is destructed before is closed the destructor calls the member function the destructor calls the member function close().close().
1515
Reaching the End of FileReaching the End of File The method The method eof()eof() determines if the end of the file is reached. determines if the end of the file is reached.
// the following program reads lines and displays// them on the screen until the end of the file.#include <iostream>#include <fstream>using namespace std;int main() { fstream myFile; char str[256]; myFile.open("data.txt", ios::in); if (myFile.is_open()) { while(!myFile.eof()) { myFile.getline(str,256); // get a line cout << str << endl; // display line } myFile.close(); } else cout << ”Unable to open file”; return 0;}
1616
Using method Using method good()good() The method The method good() good() can be used instead of the method can be used instead of the method eof()eof() . .
// the following program reads lines and displays// them on the screen until the end of the file.#include <iostream>#include <fstream>using namespace std;int main() { fstream myFile; char str[256]; myFile.open("data.txt", ios::in); if (myFile.is_open()) { while(myFile.good()) { myFile.getline(str,256); // get a line cout << str << endl; // display line } myFile.close(); } else cout << ”Unable to open file”; return 0;}
1717
Writing to a FileWriting to a File Similar to opening for reading, but use Similar to opening for reading, but use
ios::outios::out when opening: when opening:
myFile.open("data.txt", ios::out);myFile.open("data.txt", ios::out);
Consequences to file:Consequences to file: If the file does not exist, it is created.If the file does not exist, it is created. If it exists its data is overwritten.If it exists its data is overwritten.
Writing to a file:Writing to a file:
myFile << ”Hello” << 12 << ’C’ << endl;myFile << ”Hello” << 12 << ’C’ << endl;
1818
Copying a File to Another FileCopying a File to Another File#include <iostream>#include <fstream>using namespace std;int main() { fstream fin, fout; char str[256];
fin.open("data.txt", ios::in); if (fin.is_open()) { fout.open("newdata.txt", ios::out);
while(!fin.eof()) { fin.getline(str, 256); // get a line fout << str << endl; // put a line } } fin.close(); fout.close(); return 0;}
1919
Appending to a FileAppending to a File
Data can be appended at the end of the Data can be appended at the end of the file by using file by using ios::appios::app when opening. when opening.
Existing data will not be overwritten.Existing data will not be overwritten.
myFile.open("data.txt", ios::app);myFile.open("data.txt", ios::app);
2020
Constant Constant EOFEOF#include <iostream>#include <fstream>using namespace std;int main() { fstream fin, fout; char ch;
fin.open("data.txt", ios::in); if (!fin) cout << "File not found"; else { fout.open("newdata.txt", ios::out);
ch = fin.get(); while(ch != EOF) { if (ch >= ’A’ && ch <= ’Z’) fout << ’?’; else fout << ch; ch = fin.get(); } fin.close(); fout.close(); } return 0;}
My name is George andI live in London.
data.txt
?y name is ?eorge and? live in ?ondon.
newdata.txt
Character denoting the end
of file
2121
Stream Pointers: Stream Pointers: getget and and putput
All i/o stream objects have, at least, one internal stream All i/o stream objects have, at least, one internal stream pointer:pointer: ifstreamsifstreams like like istreamistream, has a pointer known as , has a pointer known as get pointerget pointer that that
points to the element to be read in the next input operation.points to the element to be read in the next input operation. ofstreamsofstreams like like ostreamostream, has a pointer known as , has a pointer known as put pointer put pointer that that
points to the location where the next element will be written.points to the location where the next element will be written. These internal stream pointers that point to the reading These internal stream pointers that point to the reading
or writing locations within a stream can be manipulated or writing locations within a stream can be manipulated using the following member functions:using the following member functions: tellg() tellg() and and tellp() tellp() – These two functions return a value of the – These two functions return a value of the
member type member type pos_typepos_type, which is an integer data type, , which is an integer data type, representing the current position of the respective pointer.representing the current position of the respective pointer.
seekg(position)seekg(position) and and seekp(position) seekp(position) – These functions change the – These functions change the position of the respective pointers. The pointer is changed to the position of the respective pointers. The pointer is changed to the absolute position absolute position (counting from the beginning of the file). (counting from the beginning of the file). Parameter position is of member type Parameter position is of member type pos_typepos_type (integer). (integer).
2222
Stream PointersStream Pointers
#include <iostream>#include <fstream>using namespace std;
int main() { ifstream fin(”data.txt”); if (fin.fail()) cout << "File not found"; else { char ch; while(ch = fin.get(), ch != EOF) { cout << ch; if (fin.tellg()==fstream::pos_type(7)) fin.seekg(18); } fin.close(); } return 0;}
My name is George andI live in London.
data.txt
My nameandI live in London
2323
Overloaded Methods forOverloaded Methods forchanging the Stream Pointerschanging the Stream Pointers
There is an overloaded function for both member functions There is an overloaded function for both member functions seekg seekg and and seekp:seekp:
direction
Description
ios::beg offset counted from the beginning of the stream
ios::cur offset counted from the current position of the stream pointer
ios::end offset counted from the end of the stream
The position of the get or put pointer is set to an offset value The position of the get or put pointer is set to an offset value relative torelative to some specific point determined by the parameter some specific point determined by the parameter directiondirection. Parameter . Parameter offsetoffset is of the member type is of the member type off_typeoff_type, , which is an integer type and which is an integer type and directiondirection is of type is of type seekdirseekdir which which is an enumerated type that determines the point from where is an enumerated type that determines the point from where offset is counted from, and that can take any of the following offset is counted from, and that can take any of the following values:values:
seekg( offset, direction )seekg( offset, direction )seekp( offset, direction )seekp( offset, direction )
2424
Changing the Stream PointersChanging the Stream PointersExamplesExamples
Code Description
seekg(0, ios::end);
Pointer get will be set at the end of the stream
seekg(-2 ,ios::end);
Pointer get will be set two positions before the end of the stream
seekg(-1, ios::cur);
Pointer get will be set one position before its current position
seekp(2, ios::beg);
Pointer put will be set two position after the beginning of the stream
myFile.seekg(0, ios::end);myFile.seekg(0, ios::end);long size = myFile.tellg();long size = myFile.tellg();cout << ”Size is ” << size << ” bytes”;cout << ”Size is ” << size << ” bytes”;
Display the size of the file:Display the size of the file:
2525
Unget CharacterUnget Character
int main() { ifstream fin("data.txt"); if (fin.fail()) cout << "File not found"; else { char ch, s[100]; ch=fin.get(); fin.unget(); if (ch == 'a') { fin >> s; cout <<s<<endl; } while (ch=fin.get(), ch!=EOF) { if (ch == ' ') { ch = fin.get(); if (ch == 'a') { fin.seekg(-1,ios::cur); fin >> s; cout << s << endl; } } } fin.close(); } return 0;}
i traveled abroad to amsterdam and i wasvery happy to go aroundand see this amazing city
data.txt
abroadamsterdamandaroundandamazing
Display the words starting with ‘a’:Display the words starting with ‘a’:
fin.unget()fin.unget();;
2626
Binary FilesBinary Files In binary files, to input and output data with the extraction and insertion operators (<< and >>) and functions like getline is In binary files, to input and output data with the extraction and insertion operators (<< and >>) and functions like getline is
not efficient, since there is no need to format data, and data my not use the separation codes used by text-files to separate not efficient, since there is no need to format data, and data my not use the separation codes used by text-files to separate elements (like spaces, newlines, etc.)elements (like spaces, newlines, etc.)
For binary files, file streams include two member functions for input and output.For binary files, file streams include two member functions for input and output.
where where memory_blockmemory_block is the address of an array of bytes and is the address of an array of bytes and sizesize is an integer. is an integer.
read( read( char*char* memory_block, memory_block, intint size ) size ) – ifstream, fstream– ifstream, fstreamwrite( write( char*char* memory_block, memory_block, intint size ) size ) – ofstream, – ofstream,
fstreamfstream
2727
Writing Structures to Binary Files Writing Structures to Binary Files class human {public: human(){} human(char s[], int x) { strcpy(name,s); age = x; }private: char name[50]; int age;};
void write_to_file(){ char name[50]; int age; cout << "Enter name and age: "; cin >> name >> age; human person(name,age); ofstream myFile("data.bin", ios::app | ios::binary); myFile.write((char*)&person, sizeof(human)); myFile.close();}
2828
Reading Structures from Binary Reading Structures from Binary Files Files
void read_from_file(human people[], unsigned long &n) { ifstream myFile("data.bin", ios::binary); if (myFile.fail()) cout << "File not found"; else { myFile.seekg(0,ios::end); n = myFile.tellg()/sizeof(human); myFile.seekg(0); for (unsigned long i=0; i<n; i++) myFile.read((char*)&people[i], sizeof(human)); myFile.close(); }}
void read_from_file(human people[], unsigned long &n) { ifstream myFile("data.bin", ios::binary); if (myFile.fail()) cout << "File not found"; else { myFile.seekg(0,ios::end); n = myFile.tellg()/sizeof(human); myFile.seekg(0); myFile.read((char*)people, sizeof(human)*n); myFile.close(); }}
Reading records one-
by-one
Reading records all at
once
2929
Buffers and SynchronizationBuffers and Synchronization File streams are associated to an internal buffer of type File streams are associated to an internal buffer of type streambufstreambuf. This . This
buffer is a memory block that acts as an intermediary between the stream buffer is a memory block that acts as an intermediary between the stream and the physical file. For example, with an and the physical file. For example, with an ofstreamofstream, each time the member , each time the member function function putput (which writes a single character) is called, the character is not (which writes a single character) is called, the character is not written directly to the physical file with which the stream is associated. written directly to the physical file with which the stream is associated. Instead, the character is inserted in the stream’s intermediate buffer.Instead, the character is inserted in the stream’s intermediate buffer.
When the buffer is flushed, all the data contained in it is written to the When the buffer is flushed, all the data contained in it is written to the physical medium (if it is an output stream) or freed (if it is an input stream). physical medium (if it is an output stream) or freed (if it is an input stream). This process is called This process is called synchronizationsynchronization and takes place under the following and takes place under the following circumstances:circumstances: When the file is closedWhen the file is closed: before closing a file all buffers that have not yet been : before closing a file all buffers that have not yet been
flushed are synchronized and all pending data is written or read to the physical flushed are synchronized and all pending data is written or read to the physical medium.medium.
When the buffer is fullWhen the buffer is full: Buffers have a certain size. When the buffer is full it : Buffers have a certain size. When the buffer is full it automatically synchronized.automatically synchronized.
Explicitly, with manipulatorsExplicitly, with manipulators: When certain manipulators are used on streams, : When certain manipulators are used on streams, an explicit synchronization takes place. These manipulators are: an explicit synchronization takes place. These manipulators are: flushflush and and endlendl..
Explicitly, with member function Explicitly, with member function sync()sync(): calling stream’s member function : calling stream’s member function sync(), which takes no parameters, causes an immediate synchronization. This sync(), which takes no parameters, causes an immediate synchronization. This function returns an int value equal to -1 if the stream has no associated buffer or function returns an int value equal to -1 if the stream has no associated buffer or in the case failure. Otherwise (if successful) it returns 0.in the case failure. Otherwise (if successful) it returns 0.
top related