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.

Slides:



Advertisements
Similar presentations
CMSC 2021 C++ I/O and Other Topics. CMSC 2022 Using C++ Stream I/O Default input stream is called cin Default output stream is called cout Use the extraction.
Advertisements

1 Classes and Data Abstraction and File Processing Lecture 13.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
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.
CPSC 231 D.H. C++ File Processing 1 Learning Objectives §C++ I/O streams. §Reading and writing sequential files. §Reading and writing random access files.
 2006 Pearson Education, Inc. All rights reserved File Processing.
計算機概論實習 Files and Streams C++ views file as sequence of bytes Ends with end-of-file marker n-1 end-of-file marker 67 This is.
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.
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.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 13: Advanced File.
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.
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.
 2008 Pearson Education, Inc. All rights reserved File Processing.
計算機程式語言 Lecture 17-1 國立台灣大學生物機電系 林達德 17 File Processing.
“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.
I/O in C++ October 7, Junaed Sattar. Stream I/O a stream is a flow of bytes/characters/ints or any type of data input streams: to the program output.
C++ FILE I/O.
File I/O in C++ II. Open() function Open() is a member function in each classes ( fstream, ifstream, ofstream) Void fstream :: open ( const char *filename,
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.
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.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 1 due Friday, 7pm. RAD due next Friday. Presentations week 6. Today: –More details on functions,
1 CSC241: Object Oriented Programming Lecture No 32.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
File Processing Files are used for data persistance-permanent retention of large amounts of data. Computer store files on secondary storage devices,such.
1 Today’s Objectives  Announcements Homework #5 is due next Monday, July 24. Since this date is so close to the end of the semester, no late assignments.
Exploring the C++ Stream Library Copyright 2006 Oxford Consulting, Ltd1 February IO Streams  IOStreams are part of the Standard C++ library.
Learners Support Publications Working with Files.
CSCI 333 Data Structures I/O with C++ 20 October, 2003.
1 Object Oriented Data Structures CSIS2020 File I/O in C++
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)
CSE 232: Moving Data Within a C++ Program Moving Data Within a C++ Program Input –Getting data from the command line (we’ve looked at this) –Getting data.
KBD Program with file I/O Operation File Disk Program with file I/O Operation Screen Cin Cout.
Ms N Nashandi Dr SH Nggada 2016/01/03Ms N Nashandi and Dr SH Nggada1 Week 6 -File input and output in C++
2008YeungNam Univ. SE Lab. 1 C++ views each file as a sequence of bytes terminated by EOF-marker. Header files Files are opened by creating objects of.
CS212: Object Oriented Analysis and Design
Programming with ANSI C ++
17 File Processing.
Chapter 13: Advanced File and I/O Operations
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
C++ FileIO pepper.
Topics Input and Output Streams More Detailed Error Testing
Chapter 12: Advanced File Operations.
Data File Handling in C++
C++ Programming: chapter 6 – iostream
Data File Handling RITIKA SHARMA.
C++ Programming Lecture 8 File Processing
File I/O in C++ II.
Presentation transcript:

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 or binary)int –doublearray,...

fstream methods For files, cin.get( obj ); cout.put( obj ); get() extracts one value from input buffer put() inserts one value into output buffer

Sequential Access Files File accessed in same order as written Next input extraction picks up where last input extraction left off. File is stream of elements File may be of varying sizes Limiting (think: cassette tape )

Random Access Files Read and write fixed-length records that contain fields (like C++ structure or class) Files can be accessed sequentially Files can be accessed randomly (think: CDs ) File pointer must be positioned before input extraction operation for random access Each record logically has relative record number (similar to index of arry, 0..n-1)

Sequential vs. Random Access Random requires fixed-length records Can contain characters, strings, ints, floats, struct or object instance Can be written in –text format (character by character) –non-text (binary; written using same internal format as in memory)

Open Method filePtr.open (filename, access mode) ifstream ifs; ofstream ofs; Open input file ifs.open (“names.txt”, ios::in); Open output file ofs.open (“names.txt”, ios::out);

Open Access Modes ModeDescription in Open for reading out Open for writing app Open for appending at end binary Opens in binary mode (non-text) to save space (no conversion)

Open Examples Create file, write to it, and change some data ofs.open(“names.dat”, ios::in | ios::out); Create file and make changes, all in non-text mode ofs.open(“names.dat”, ios::in | ios::out | ios::binary);

fstream Methods for Random Access tellg() - returns (in bytes) location of file pointer in input file tellp() - returns (in bytes) location of file pointer in output file seekg() - repositions current file pointer in input file seekp() - repositions current file pointer on output file If both in and out, use tellg() and seekg()

seekg() Method Moves the file pointer to a specific point in random-access data file Format is: file.seekg(longNum, origin) – file - already initialized with open() – longNum - number of bytes to skip – origin - where to begin seeking seekp() similar for output files

Values for origin C++ nameDescription ios::beg Beginning of file ios::cur Current file position ios::end End of file (all defined in fstream.h)

Examples of seekg() Position file pointer at beginning of file ofs.seekg( 0L, ios::beg); 0L (zero L) is constant long integer zero Moves file pointer zero bytes from beginning of the file

Example program using seekg() to read file twice void main() { char inChar; ifstream inFile; ofstream scrnl; inFile.open(“MYFILE.TXT”,ios::in); scrn.open(“CON”, ios::out); if (!inFile) { cout << “Error opening MYFILE.TXT”; exit(0);} while (inFile >> inChar) scrn << inChar; scrn.close(); inFile.clear(); // reset EOF1 inFile.seekg(0L, ios::begin); // to beginning while (inFile >> inChar) cout << inChar; inFile.close(); } See Fileio1.cpp

seekg() with file of structures or objects Suppose have file of structures (inventory records) Want 123rd occurrence of inventory record Use sizeof() function filePtr.seekg( (123L * sizeof(struct inventory)), ios::beg);

Binary I/O Requires primitive read and write methods write (address, size) read (address, size) – address - pointer to buffer of data (can be array of bytes or structure) – size - number of bytes to transfer; sizeof(datatype) function useful

Example of non-text mode with standard datatypes ofstream outFile; outFile.open(“myfile.dat”, ios::in|ios::out|ios::binary); int data = 30; int A[20]; outFile.write((char *) & data, sizeof(int)); outFile.write((char *) A, 20*sizeof(int)); outFile.seekg(0L, ios::beg); outFile.read((char *) A, 20*sizeof(int));

Example with objects - 1 #include class person { public: void getData(void); void showData(void); protected: char name[40]; int age; };

Example with objects - 2 void person::getData(void) { cout > name; cout > age; } void person::showData(void) { cout << “Name: “ << name; cout << “Age: “ << age; }

Example with objects - 3 #include void main(void) //create file of person objects { char ch; person pers; ofstream file; file.open (“PERSON.DAT”, ios::binary); do { cout << “Enter person’s data:”; pers.getData(); file.write((char*) &pers, sizeof(pers)); cout << “Enter another person(y/n)?”; cin >> ch; } while (ch == ‘y’); } Fileio3.ide

Example with objects - 4 #include void main(void) //read file of person objects { char ch; person pers; ifstream file; file.open (“PERSON.DAT”, ios::binary); while (file.read((char *) &pers, sizeof(pers)) ) { cout << “Person”; pers.showData(); } Fileio4.ide

Define a random access non-text stream class template class rstream { public: rstream (string& name); int get (unsigned int index, T & value); void put (unsigned int index, T & value); unsigned int length(); protected: fstream theStream; };

rstream constructor template rstream::rstream (string& name) { // construct an instance of rstream // convert string into C-style pointer variable char * cName = name.c_str(); // open the file for both input and output theStream.open (cName, ios::in | ios::out | ios::binary); }

put method for rstream template void rstream::put (unsigned int index, T & value) { // place a value into a random access stream // first position the stream theStream.seekg ( sizeof (T)* index ); // then write the value char & valuePtr = (char *) & value; theStream.write (valuePtr, sizeof(T)); }

get method for rstream template int rstream::get (unsigned int index, T & value) { // read a value from a random access stream // first position the stream theStream.seekg ( sizeof (T)* index ); // then read the value char & valuePtr = (char *) & value; theStream.read (valuePtr, sizeof(T)); // return the number of bytes read return theStream.gcount(); }

length method for rstream template unsigned int rstream::length ( ) { // return number of elements held in collection // first seek to end theStream.seekg ( 0L, ios::end ); // then divide current byte offset // by size of elements return theStream.tellg() / sizeof(T); }

References Ford, William and William Topp Data structures with C++. Englewood Cliffs: Prentice Hall. Lafore, Robert The Waite Group’s object-oriented programming in C++. Corte Madera, California: Waite Group Press. Perry, Greg C++ programming 101. Sams Publishing.