Learners Support Publications www.lsp4you.com Working with Files.

Slides:



Advertisements
Similar presentations
File I/O in C++. Using Input/Output Files A computer file is stored on a secondary storage device (e.g., disk);is stored on a secondary storage device.
Advertisements

Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 13 Advanced.
Copyright © 2012 Pearson Education, Inc. Chapter 12: Advanced File Operations.
17 File Processing. OBJECTIVES In this chapter you will learn:  To create, read, write and update files.  Sequential file processing.  Random-access.
Chapter 15.
Chapter 8: I/O Streams and Data Files. In this chapter, you will learn about: – I/O file stream objects and functions – Reading and writing character-based.
Tutorial4us.com. File A file is a collection of related data stored in a particular area on the disk. The data is stored in disk using the concept of.
1 File I/O In C++, I/O occurs in streams. A stream is a sequence of bytes Each I/O device (e.g. keyboard, mouse, monitor, hard disk, printer, etc.) receives.
Files. 2 Stream Stream is a sequence of bytes Input stream In input operations, the bytes are transferred from a device to the main memory Output stream.
CSE Lectures 22 – Huffman codes
COIT29222-Structured Programming Lecture Week 12  Reading: Textbook (4 th Ed.), Chapter 14 Textbook (6 th Ed.), Chapter 17 Study Guide Book 3, Module.
CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
C++ for Engineers and Scientists Second Edition Chapter 8 I/O File Streams and Data Files.
FILE HANDLING IN C++.
Topics 1.File Basics 2.Output Formatting 3.Passing File Stream Objects to Functions 4.More Detailed Error Testing 5.Member Functions for Reading and 6.Writing.
Advanced File Operations Chapter File Operations File: a set of data stored on a computer, often on a disk drive Programs can read from, write to.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 12: Advanced File Operations.
Programming Principles II Lecture Notes 7 Files Andreas Savva.
STL List // constructing lists #include int main () { // constructors used in the same order as described above: std::list first; // empty list of ints.
File handling in C++ BCA Sem III K.I.R.A.S. Using Input/Output Files Files in C++ are interpreted as a sequence of bytes stored on some storage media.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Stack/Queue - File Processing Lecture 10 March 29, 2005.
An Introduction to Programming with C++ Sixth Edition Chapter 14 Sequential Access Files.
“After a day spent staring at a computer monitor, think of a book as a kind of screen saver for your brain” “One good reason why computers can do more.
File I/O. fstream files File: similar to vector of elements Used for input and output Elements of file can be –character (text)struct –object (non-text.
C++ FILE I/O.
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.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 13 File Input and.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 12 Advanced File Operations.
File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.
DCT1063 Programming 2 CHAPTER 3 FILE INPUT AND FILE OUTPUT Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Member Functions for Reading and Writing Files 12.5.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Streams, and File I/O Review. STREAMS Review STREAMS Streams are sequences of bytes. C++ I/0 occurs in streams Input – bytes flow from device to memory.
File Handling. Read data from file and display it on screen #include int main() { /* fin object is created with parameterzied constructor */ ifstream.
1 CSC241: Object Oriented Programming Lecture No 32.
File Processing Files are used for data persistance-permanent retention of large amounts of data. Computer store files on secondary storage devices,such.
Declaring fstream Objects An istream object named cin connects program and keyboard An ostream object named cout connects the program and the screen These.
Exploring the C++ Stream Library Copyright 2006 Oxford Consulting, Ltd1 February IO Streams  IOStreams are part of the Standard C++ library.
CSCI 333 Data Structures I/O with C++ 20 October, 2003.
Lecture 14 Arguments, Classes and Files. Arguments.
FILE HANDLING(WORKING WITH FILES) FILE- A file is a collection of related data stored in a particular area on the disk. STREAMS- interface between the.
Binary Files. Text Files vs. Binary Files Text files: A way to store data in a secondary storage device using Text representation (e.g., ASCII characters)
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.
Advanced File Operations Chapter File Operations File: a set of data stored on a computer, often on a disk drive Programs can read from, write to.
Data File Handling in C++ Data File Handling in C++ Paritosh Srivastava PGT (Comp. Science) Kendriya VidyalayaJoshimath.
File Handling. Read data from file and display it on screen #include int main() { /* fin object is created with parameterzied constructor */ ifstream.
Ms N Nashandi Dr SH Nggada 2016/01/03Ms N Nashandi and Dr SH Nggada1 Week 6 -File input and output in C++
Programming II I/O Streams and Data Files 1(c) Asma AlOsaimi.
CS212: Object Oriented Analysis and Design
Chapter 14: Sequential Access Files
Programming with ANSI C ++
17 File Processing.
Tutorial4us.com File Handling in C++ Tutorial4us.com.
Data File Handling in C++
What is a File? A file is a collection on information, usually stored on a computer’s disk. Information can be saved to files and then later reused.
C ++ MULTIPLE CHOICE QUESTION
CPSC 231 D.H. C++ File Processing
FILE HANDLING IN C++.
17 File Processing.
آشنایی با ساختارها و کار با فایلها
files Dr. Bhargavi Goswami Department of Computer Science
Chapter 13: Advanced File and I/O Operations
Tutorial4us.com. File A file is a collection of related data stored in a particular area on the disk. The data is stored in disk using the concept of.
Topics Input and Output Streams More Detailed Error Testing
Chapter 12: Advanced File Operations.
Data File Handling in C++
Data File Handling RITIKA SHARMA.
File I/O in C++ II.
UNIT-V Files.
Presentation transcript:

Learners Support Publications Working with Files

Learners Support Publications File Input and Output Stream  C++ uses file streams as an interface between the programs and the data files. Disk FilesProgram Output Stream Data output Data input Input Stream Write Data Read Data

Learners Support Publications File Input and Output Stream Disk FilesProgram Output Stream Data output Data input Input Stream Write Data Read Data The stream that supplies data to the program is known as input stream The stream that receives data from the program is known as output stream Input stream extracts (or read) data from file Output stream inserts (or writes) data to the file

Learners Support Publications Opening Files  For opening a file, we must first create a file stream and then link it to the filename.  A file stream can be defined using the classes ifstream, ofstream, and fstream that are contained in the header file fstream.  The class to be used depends on read or write.  A file can be open in two ways: Using the constructor function of the class. Using the constructor function of the class. Useful when we use only one file in the stream.Useful when we use only one file in the stream. Using the member function open( ) of the class. Using the member function open( ) of the class. Use to manage multiple files using one stream.Use to manage multiple files using one stream.

Learners Support Publications Opening Files Using Constructor  This involves two steps: Create a file stream object to manage the stream using appropriate class. Create a file stream object to manage the stream using appropriate class. The class ofstream used to create output stream.The class ofstream used to create output stream. The class ifstream to create input stream.The class ifstream to create input stream. Initialize the file object with the desired filename. Initialize the file object with the desired filename.

Learners Support Publications Opening Files Using Constructor  ofstream outfile (“results”);  ifstream infile(“data”); continue … Program Output Stream outfile infile Input Stream Disk Result File Data File

Learners Support Publications Opening Files Using Open( )  The open( ) can be used to open multiple files that use the same stream object.  For processing a set files sequentially. file-stream-class stream-object; stream-object.open ( “file_name” );

Learners Support Publications Opening Files Using Open( ) ofstream outfile; outfile.open(“DATA1”);…….. outfile.close( ); outfile.open(“DATA2”);………  The above program segment opens two files in sequence for writing the data.  The first file is closed before opening the second one.  A stream can be connected to only one file at a time. continue …

Learners Support Publications Detecting End-Of-File  while (fin) An ifstream object fin returns a value 0 if any error occurs in the file operation including the end-of-file condition. An ifstream object fin returns a value 0 if any error occurs in the file operation including the end-of-file condition. So the while loop may terminates when fin returns a value of zero on reaching the end-of-file condition. So the while loop may terminates when fin returns a value of zero on reaching the end-of-file condition.  if(fin1.eof() != 0) {exit(1);} eof( ) is a member of ios class. eof( ) is a member of ios class. It returns a non-zero value if the end-of-file (EOF) condition is encountered, and a zero, otherwise. It returns a non-zero value if the end-of-file (EOF) condition is encountered, and a zero, otherwise.

Learners Support Publications File Modes  stream-object.open(“file_name”, mode); The second argument mode specifies the purpose for which the file is opened. The second argument mode specifies the purpose for which the file is opened. Default values for these second parameters: Default values for these second parameters: ios::in – for ifstream - reading onlyios::in – for ifstream - reading only ios::out – for ofstream - writing onlyios::out – for ofstream - writing only

Learners Support Publications File Modes  ios::app  Append to end-of-file  ios::ate  Go to end-of-file on opening  ios::binary  Binary file  ios::in  Open file for reading only  ios::nocreate  Open fails if the file does not exist  ios::noreplace  Open files if the file already exists  ios::out  Open file for writing only  ios::trunc  Delete the contents of the file if it exists fout.open(“data”, ios::app | ios :: nocreate) continue …

Learners Support Publications File Pointer  Input Pointer (get pointer) The input pointer is used for reading contents of a given file location. The input pointer is used for reading contents of a given file location.  Output Pointer (put pointer) The output pointer is used for writing to a given file location. The output pointer is used for writing to a given file location.  Each time an input or output operation takes place, the appropriate pointer is automatically advanced.

Learners Support Publications File Pointer – Default Actions  When a file opened in read-only mode, the input pointer is automatically set at the beginning of the file.  When a file is opened in write-only mode, the existing contents are deleted and the output pointer is set at the beginning.  When a file is opened in append mode, the output pointer moves to the end of file.

Learners Support Publications Functions for Manipulations of File Pointers  seekg( )  Moves get pointer (input) to a specified location.  seekp( )  Moves put pointer(output) to a specified location.  tellg( )  Gives the current position of the get pointer.  tellp( )  Gives the current position of the put pointer.

Learners Support Publications Seek Function with Absolute Position  infile.seekg(10); Moves the file pointer to the byte number 10. The bytes in a file are numbered beginning from zero. Therefore, the pointer pointing to the 11 th byte in the file.

Learners Support Publications Seek Function with Specifying the Offset  seekg( offset, refposition);  seekp( offset, refposition); The parameter offset represents the number of bytes the file pointer is to be moved from the location specified by the parameter refposition. The refposition takes one of the following three constants defined in the ios class: ios : : beg  start of the file ios : : beg  start of the file ios : : cur  current position of the pointer ios : : cur  current position of the pointer ios : : end  end of the file ios : : end  end of the file

Learners Support Publications Seek Function with Specifying the Offset fout.seekg(0, ios : : beg); Go to start fout.seekg(0, ios : : cur); Stay at the current position fout.seekg(0, ios : : end); Go to the end of file fout.seekg(m, ios : : beg); Move to (m+1)th byte in the file fout.seekg(m, ios : : cur); Go forward by m bytes from the current position fout.seekg(-m, ios : : cur); Go backward by m bytes from the current position fout.seekg(-m, ios : : end) Go backward by m bytes from the end

Learners Support Publications Sequential Input and Output Operations  put( ) and get( ) Functions The function put( ) writes a single character to the associated stream. The function put( ) writes a single character to the associated stream. The function get( ) reads a single charracter from the associated stream. The function get( ) reads a single charracter from the associated stream.

Learners Support Publications Sequential Input and Output Operations  write( ) and read( ) Functions The functions write( ) and read ( ) handle the data in binary form. The functions write( ) and read ( ) handle the data in binary form. The values are stored in the disk file in the same format in which they are stored in the internal memory. The values are stored in the disk file in the same format in which they are stored in the internal memory. An int takes two bytes to store its value in the binary form, irrespective of its size. An int takes two bytes to store its value in the binary form, irrespective of its size. But a 4 digit int will take four bytes to store it in the character form. But a 4 digit int will take four bytes to store it in the character form. continue …

Learners Support Publications Sequential Input and Output Operations Representing 2594 continue … Binary Format Character Format 4 Bytes I I 2 Bytes I I

Learners Support Publications Sequential Input and Output Operations  infile.read((char *) &V, sizeof(V));  outfile.write((char *) &V, sizeof(V));  write( ) and read( ) functions take two arguments.  First is the address of the variable V  Second is the length of that variable in bytes.  The address of the variable must be cast to type char * (pointer to character type). continue …

Learners Support Publications Reading and Writing a Class Object  The read( ) and write( ) are also used to read from or write to the disk files objects directly.  The read( ) and write( ) handle the entire structure of an object as a single unit, using the computer’s internal representation of data.  Only data members are written to the disk files.

Learners Support Publications Updating A File : Random Access  The size of each object can be obtained using the statement int object_length = sizeof(object);  The location of a desired object, say mth object int location = m * object_length; The location gives the byte number of the first byte of the mth object.  Now we can use seekg( ) or seekp( ) to set the file pointer to reach this byte.

Learners Support Publications Updating A File : Random Access  To find the total number of objects in a file using object_length int n = file_size / object_length;  The file size can be obtained using the function tellg( ) or tellp( ) when the pointer is located at the end of the file. continue …

Learners Support Publications Error Handling During File Operations  A file which we are attempting to open for reading does not exist.  The file name used for a new file may already exist.  We may attempt an invalid operation such as reading past the end-of-file.  There may not be any space in the disk for storing more data.  We may use an invalid file name.  We may attempt to perform an operation when the file is not opened for that purpose.

Learners Support Publications Error Handling During File Operations  The C++ file stream inherits a “stream_state” member from the class ios.  This member records information on the status of a file that is being currently used.  The class ios supports several member functions that can be used to read the status recorded in a file stream.  eof( )  fail( )  bad( )  good( ), etc. continue …

Learners Support Publications Command – Line Arguments  C++ supports a feature that facilitates the supply of argument to the main( ) function.  These arguments are supplied at the time of invoking the program.  They are typically used to pass the names of data files. Eg:- exam data result Eg:- exam data result  The command-line arguments are typed by the user and are delimited by a space.

Learners Support Publications Command – Line Arguments  The main function can take two arguments.  main( int argc, char * argv [ ] )  The first argument argc (argument counter) represents the number of arguments in the command line.  The second argument argv (argument vector) is an array of char type pointers that points to the command line arguments.  The size of the array will be equal to the value of argc. continue …

Learners Support Publications Command – Line Arguments  C:\> exam data results  The value of argc would be 3 and argv would be an array of three pointers to strings as: argv[0]  exam argv[0]  exam argv[1]  data argv[1]  data argv[2]  results argv[2]  results ………… infile.open(argv[1]);infile.open(argv[1]); ………… outfile.open(argv[2]);outfile.open(argv[2]); ………… continue …

Learners Support Publications Thank You Learners Support Publications