17 files and streams
Upcoming SlideShare
Loading in...5

17 files and streams



Files and Streams

Files and Streams



Total Views
Views on SlideShare
Embed Views



1 Embed 5

https://tasks.crowdflower.com 5



Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment

17 files and streams 17 files and streams Presentation Transcript

  • Files and Streams 09/04/131 VIT - SCSE By G.SasiKumar., M.E., (Ph.D)., Assistant Professor School of Computing Science and Engineering VIT University
  • 09/04/132 VIT - SCSE Files Diskette Memory Input file Output file Used to transfer data to and from disk
  • 09/04/133 VIT - SCSE Streams Stream a channel or medium where data are passed to receivers from senders. Output Stream a channel where data are sent out to a receiver cout; the standard output stream (to monitor) the monitor is a destination device Input Stream a channel where data are received from a sender cin; the standard input stream (from the keyboard) the keyboard is a source device
  • 09/04/134 VIT - SCSE Standard Input / Output Streams Standard Streams use #include <iostream.h> Standard Input Stream cin names the stream the extractor operator >> extracts, gets, or receives the next element from the stream Standard Output Stream cout names the stream the inserter operator << inserts, puts, or sends the next element to the stream Opening & closing of the standard streams occur automatically when the program begins & ends.
  • 09/04/135 VIT - SCSE File Streams Files data structures that are stored separately from the program (using auxiliary memory) streams must be connected to these files Input File Stream extracts, receives, or gets data from the file Output File Stream inserts, sends, or puts data to the file #include <fstream.h> creates two new classes ofstream (output file stream) ifstream (input file stream)
  • 09/04/136 VIT - SCSE C++ Files and Streams C++ views each files as a sequence of bytes. Each file ends with an end-of-file marker. When a file is opened, an object is created and a stream is associated with the object. To perform file processing in C++, the header files <iostream.h> and <fstream.h> must be included. <fstream.> includes <ifstream> and <ofstream>
  • 09/04/137 VIT - SCSE
  • 09/04/138 VIT - SCSE File Handling Classes Hierarchy Diagram
  • 09/04/139 VIT - SCSE iosios streambufstreambuf ostreamostreamistreamistream iostreamiostream fstreamfstream filebuffilebuf ofstreamofstreamifstreamifstream fstreambasefstreambase
  • 09/04/1310 VIT - SCSE Opening Files Use open function or include file name when declaring variable: ifstream inobj1; inobj1.open(“in1.dat”) ifstream inobj2(“in2.dat”); To check if file successfully opened check object in condition: if (!inobj1)  cout << “Unable to open file in1.dat” << endl;
  • 09/04/1311 VIT - SCSE Opening Output Files Ofstream outClientFile(“clients.dat”, ios:out) OR Ofstream outClientFile; outClientFile.open(“clients.dat”, ios:out) Example ofstream out(“outf”,ios::out | ios::append); // out is an append connection to outf
  • 09/04/1312 VIT - SCSE File Open Modes ios:: app - (append) write all output to the end of file ios:: ate - data can be written anywhere in the file ios:: binary - read/write data in binary format ios:: in - (input) open a file for input ios::out - (output) open a file for output ios: trunc -(truncate) discard the files’ contents if it exists ios:nocreate - if the file does NOT exists, the open operation fails ios:noreplace - if the file exists, the open operation fails
  • 09/04/1313 VIT - SCSE Closing a File Use close() on object to close connection to file: ifstream in(“in.dat”); … in.close();
  • 09/04/1314 VIT - SCSE #include <stdlib.h> #include <iostream.h> #include <fstream.h> void main() { char infname[101]; char outfname[101]; char buffer[101]; cout << ”File to copy from: "; cin >> infname; ifstream in(infname); if (!in) { cout << "Unable to open " << infname << endl; exit(0); } cout << "File to copy to: "; cin >> outfname; ofstream out(outfname,ios::out | ios::noreplace); if (!out) { cout << "Unable to open " << outfname << " -- already exists!" << endl; exit(0); } in.getline(buffer,100); while (!in.eof()) { out << buffer << endl; in.getline(buffer,100); } in.close(); out.close(); }
  • Using Sequential Access Files A sequential access file is often called a text file  Bit - smallest data item value of 0 or 1  Byte – 8 bits  used to store a character  Decimal digits, letters, and special symbols  Field - group of characters conveying meaning Example: your name  Record – group of related fields Represented a struct or a class Example: In a payroll system, a record for a particular employee that contained his/her identification number, name, address, etc.  File – group of related records Example: payroll file  Database – group of related files 09/04/1315 VIT - SCSE
  • 09/04/1316 VIT - SCSE The Data Hierarchy Record key identifies a record to facilitate the retrieval of specific records from a file Sequential file  records typically sorted by key 1 01001010 Judy Judy Green Sally Black Tom Blue Judy Green Iris Orange Randy Red File Record Field Byte (ASCII character J) Bit
  • 09/04/1317 VIT - SCSE Files and Streams C++ views each file as a sequence of bytes File ends with the end-of-file marker Stream created when a file is opened File processing Headers <iostream.h> (cout, cin, cerr, clog) and <fstream.h> class ifstream - input class ofstream - output class fstream - either input or output
  • 09/04/1318 VIT - SCSE Creating a Sequential Access File Files are opened by creating objects of stream classes ifstream, ofstream or fstream File stream member functions for object file: file.open(“Filename”, fileOpenMode); file.close(); destructor automatically closes file if not explicitly closed File open modes: Mode Description ios::app Write all output to the end of the file. ios::ate Open a file for output and move to the end of the file (normally used to append data to a file). Data can be written anywhere in the file. ios::in Open a file for input. ios::out Open a file for output. ios::trunc Discard the file’s contents if it exists (this is also the default action for ios::out) ios::binary Open a file for binary (i.e., non-text) input or output. Makes a "line of communication" with the object and the file.
  • 09/04/1319 VIT - SCSE File position pointer <istream> and <ostream> classes provide member functions for repositioning the file pointer (the byte number of the next byte in the file to be read or to be written.) These member functions are: seekg (seek get) for istream class seekp (seek put) for ostream class
  • 09/04/1320 VIT - SCSE Examples of moving a file pointer inClientFile.seekg(0) - repositions the file get pointer to the beginning of the file inClientFile.seekg(n, ios:beg) - repositions the file get pointer to the n-th byte of the file inClientFile.seekg(m, ios:end) -repositions the file get pointer to the m-th byte from the end of file nClientFile.seekg(0, ios:end) - repositions the file get pointer to the end of the file The same operations can be performed with <ostream> function member seekp.
  • 09/04/1321 VIT - SCSE Member functions tellg() and tellp(). Member functions tellg and tellp are provided to return the current locations of the get and put pointers, respectively. long location = inClientFile.tellg(); To move the pointer relative to the current location use ios:cur inClientFile.seekg(n, ios:cur) - moves the file get pointer n bytes forward.
  • 09/04/1322 VIT - SCSE Updating a sequential file Data that is formatted and written to a sequential file cannot be modified easily without the risk of destroying other data in the file. If we want to modify a record of data, the new data may be longer than the old one and it could overwrite parts of the record following it.
  • Problems with sequential files Sequential files are inappropriate for so-called “instant access” applications in which a particular record of information must be located immediately. These applications include banking systems, point-of-sale systems, airline reservation systems, (or any data-base system.) 09/04/1323 VIT - SCSE
  • Random access files Instant access is possible with random access files. Individual records of a random access file can be accessed directly (and quickly) without searching many other records. 09/04/1324 VIT - SCSE
  • Creating a Random Access Filewrite - outputs a fixed number of bytes beginning at a specific location in memory to the specified stream When writing an integer number to a file, outFile.write( reinterpret_cast<const char *>( &number ), sizeof( number ) ); First argument: pointer of type const char * (location to write from) address of number cast into a pointer Second argument: number of bytes to write(sizeof(number)) recall that data is represented internally in binary (thus, integers can be stored in 4 bytes) Do not use outFile << number; could print 1 to 11 digits, each digit taking up a byte of storage 09/04/1325 VIT - SCSE
  • #include <iostream.h> #include <fstream.h> #include <stdlib.h> #include "clntdata.h" int main() { ofstream outCredit( "credit.dat", ios::ate ); if ( !outCredit ) { cerr << "File could not be opened." << endl; exit( 1 ); } cout << "Enter account number " << "(1 to 100, 0 to end input)n? "; clientData client; cin >> client.accountNumber; while ( client.accountNumber > 0 && client.accountNumber <= 100 ) { cout << "Enter lastname, firstname, balancen? "; cin >> client.lastName >> client.firstName >> client.balance; outCredit.seekp( ( client.accountNumber - 1 ) * sizeof( clientData ) ); outCredit.write( reinterpret_cast<const char *>( &client ), sizeof( clientData ) ); cout << "Enter account numbern? "; cin >> client.accountNumber; } return 0; } 09/04/1326 VIT - SCSE
  • Writing Data Randomly to a Random Access File seekp can be used in combination with write to store data at exact locations in an output file 09/04/1327 VIT - SCSE
  • Reading data from a random file #include <iostream.h> #include <iomanip.h> #include <fstream.h> #include <stdlib.h> #include "clntdata.h" void outputLine( ostream&, const clientData & ); int main() { ifstream inCredit( "credit.dat", ios::in ); if ( !inCredit ) { cerr << "File could not be opened." << endl; exit( 1 ); } cout << setiosflags( ios::left ) << setw( 10 ) << "Account" << setw( 16 ) << "Last Name" << setw( 11 ) << "First Name" << resetiosflags( ios::left ) << setw( 10 ) << "Balance" << endl; clientData client; inCredit.read( reinterpret_cast<char *>( &client ), sizeof( clientData ) ); while ( inCredit && !inCredit.eof() ) { if ( client.accountNumber != 0 ) outputLine( cout, client ); inCredit.read( reinterpret_cast<char *>( &client ), sizeof( clientData ) ); } return 0; } void outputLine( ostream &output, const clientData &c ) { output << setiosflags( ios::left ) << setw( 10 ) << c.accountNumber << setw( 16 ) << c.lastName << setw( 11 ) << c.firstName << setw( 10 ) << setprecision( 2 ) << resetiosflags( ios::left ) << setiosflags( ios::fixed | ios::showpoint ) << c.balance << 'n'; } 09/04/1328 VIT - SCSE
  • The <istream> function read inCredit.read (reinterpret_cast<char *>(&client), sizeof(clientData)); The <istream> function inputs a specified (by sizeof(clientData)) number of bytes from the current position of the specified stream into an object. 09/04/1329 VIT - SCSE