Programming Principles II Lecture Notes 7 Files Andreas Savva.

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

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.
計算機概論實習 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.
CS-212 C++ I/O Dick Steflik. C++ I/O Modeled after UNIX’s concept of a “stream” –conceptionally a stream is a continuous flow of characters/bytes from.
17 File Processing. OBJECTIVES In this chapter you will learn:  To create, read, write and update files.  Sequential file processing.  Random-access.
This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson.
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.
File input and output in C++ Dr. Ahmed Telba. CSE202: Lecture 9The Ohio State University2 Reading & Writing to Files.
Darbas su failais Arnas Terekas IT 1gr. Vilniaus universitetas Matematikos ir informatikos fakultetas.
CSIS 123A Lecture 8 Streams & File IO Glenn Stevenson CSIS 113A MSJC.
C++ for Engineers and Scientists Second Edition Chapter 8 I/O File Streams and Data Files.
File I/O ifstreams and ofstreams Sections 11.1 &
FILE HANDLING IN C++.
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.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
An Introduction to Programming with C++ Sixth Edition Chapter 14 Sequential Access Files.
Computer Programming TCP1224 Chapter 13 Sequential File Access.
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.
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.
C++ Programming: chapter 6 – iostream 2014, Spring Pusan National University Ki-Joune Li 1.
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
Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba.
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.
Input/Output CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
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.
GE 211 Programming in C ++ Dr. Ahmed Telba Room :Ac -134
C++ Programming: chapter 6 – iostream 2015, Spring Pusan National University Ki-Joune Li 1.
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.
Learners Support Publications Working with Files.
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)
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Today’s Lecture  I/O Streams  Console I/O  File I/O  Tools for File I/O  Sequential.
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.
File I/O in C++ I. Using Input/Output Files A computer file is stored on a secondary storage device (e.g., disk); is permanent; can be used to provide.
Ms N Nashandi Dr SH Nggada 2016/01/03Ms N Nashandi and Dr SH Nggada1 Week 6 -File input and output in C++
Basic file operations in C++ Dr. Ahmed Telba 1. 2 Learning Objectives §C++ I/O streams. §Reading and writing sequential files. §Reading and writing random.
Computer Programming II Lecture 9. Files Processing - We have been using the iostream standard library, which provides cin and cout methods for reading.
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 ++
What is wrong in the following function definition
ifstreams and ofstreams
Tutorial4us.com File Handling in C++ Tutorial4us.com.
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
FILE HANDLING IN C++.
آشنایی با ساختارها و کار با فایلها
files Dr. Bhargavi Goswami Department of Computer Science
Today’s Lecture I/O Streams Tools for File I/O
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++
C++ Programming: chapter 6 – iostream
ifstreams and ofstreams
File I/O in C++ I.
Presentation transcript:

Programming Principles II Lecture Notes 7 Files Andreas Savva

2 Files A file is a group of organized data stored in secondary storage. A file is a group of organized data stored in secondary storage. Every file has a filename – the name by which the operating system refers to the contents of the file. Every file has a filename – the name by which the operating system refers to the contents of the file. Dear Ann I am now living in Cyprus where I got married and bought a house. This is a great place to be. The weather is perfect and life is... Letter.txt

3 Type of Files The operating system usually distinguishes files in different categories: The operating system usually distinguishes files in 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 files in a format understood only by the specific application program e.g. Application programs usually store data in binary files in a format understood only by the specific 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)

4 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 fstream. include the library fstream. declare an object to represent a file which will permit reading, writing, etc. declare an object to represent a file which will permit reading, writing, etc. C++ provides the following classes to perform input and output from/to files: C++ provides the following classes to perform input and output from/to files: ofstream: stream class to write in files ofstream: stream class to write in files ifstream: Stream class to read from files ifstream: Stream class to read from files fstream: Stream class to read and write from/to files fstream: Stream class to read and write from/to files #include using namespace std; int main() { fstream myFile;... return 0; }

5 Opening 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 myFile.open(filename, mode) use the handle to open the file myFile.open(filename, mode) To open an existing file to read from, the mode must be ios::in. To open an existing file to read from, the mode must be ios::in. #include using namespace std; int main() { fstream myFile; myFile.open(”data.txt”,ios::in);... return 0; }

6 Using fstream Objects In using both ifstream and ofstream objects the mode, input or output, is implied by the object. Thus, In using both ifstream and ofstream objects the mode, input or output, is implied by the object. Thus, ifstream objects can only be used for input ifstream objects can only be used for input ofstream objects can only be used for output ofstream objects can only be used for output fstream objects can be used for input or output but require an explicit mode designation. fstream objects can be used for input or output but require an explicit mode designation. #include 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; }

7 Opening 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; myFile.open(”example.bin”, ios::out | ios::app | ios::bin); ModeDescription ios::inOpen a text file in input mode ios::outOpen a text file in output mode ios::appOpen a text file in append mode ios::ateGo to the end of the open file ios::binaryOpen a binary file in input mode (default is text file) ios::truncDelete file contents if file exists All these flags can be combined using the bitwise operator OR (|). For example, the following will open a the file example.bin in binary mode to add data: All these flags can be combined using the bitwise operator OR (|). For example, the following will open a the file example.bin in binary mode to add data:

8 Default Modes Each one of the open() member functions of the classes ofstream, ifstream and fstream has a default mode that is used if the file is opened without a second argument, i.e. Each one of the open() member functions of the classes ofstream, ifstream and fstream has a default mode that is used if the file is opened without a second argument, i.e. ClassDefault mode parameter ofstreamios::out ifstreamios::in fstreamios::in | ios::out The three classes have a constructor that takes the same parameters as open() and automatically calls it. The three classes have a constructor that takes the same parameters as open() and automatically calls it. ofstream myFile; myFile.open(”data.txt”); ofstream myFile(”data.txt”, ios::out);

9 Opening a File File streams opened in binary mode perform input and output operations independently of any format considerations. File streams opened in binary mode perform input and output operations independently of any format considerations. Non-binary files are known as text files, and some translations may occur due to formatting of some special characters (like newline and carriage return characters). Non-binary files are known as text files, and some translations may occur due to formatting of some special characters (like newline and carriage return characters). The method is_open() with no arguments (returns a bool value) can be called to check whether or not a file stream has successfully opened a file. The method is_open() with no arguments (returns a bool value) can be called to check whether or not a file stream has successfully opened a file. ofstream myFile(”data.txt”); if (myFile.is_open()) { // ok, proceed with output } else cout << ”Unable to open file”;

10 Reading from a Text-File #include 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 in the same way as with cout and cin. Data output and input operations on text-files are performed in the same way as with cout and cin.

11 Reading Methods There exist a variety of methods for reading streams (files). There exist a variety of methods for reading streams (files). Read a single character, including spaces and control characters: Read a single character, including spaces and control characters: 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); Read a line of text or up to 20 characters or until character ’A’ occurred into array s[] : Read a line of text or up to 20 characters or until character ’A’ occurred into array s[] :myFile.getline(s,20,’A’); cin is also a stream object; we can use the same operations: cin is also a stream object; we can use the same operations: ch = cin.get(); cin.getline(s,20);cin.getline(s,20,’A’);

12 Exceptions and Errors With file operations there may be a variety of problems, i.e. With file operations there may be a variety of problems, i.e. File not found during opening. File not found during opening. File cannot be opened (already opened exclusively by other program). File cannot be opened (already opened exclusively by 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:!myFilemyFile.fail() myFile.open("data.txt",ios::in); if (!myFile) // an error has occurred cout << ”Could not open file”;...

13 Checking State Flags A number of bool member functions exist to check for specific states of a stream: A number of bool member functions exist to check for specific states of a stream: MethodDescription 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.

14 Closing a File After completing the use of the file, it should be closed so that it resources become available again. After completing the use of the file, it should be closed so that it resources become available again. Closing a file: Closing a file:myFile.close(); Once closing the file, the file becomes available to be opened by other processes and the stream object can be used to open another file. Once closing the file, the file becomes available to be opened by other processes and the stream object can be used to open another file. In case that an object is destructed before is closed the destructor calls the member function close(). In case that an object is destructed before is closed the destructor calls the member function close().

15 Reaching the End of File The method eof() determines if the end of the file is reached. The method eof() 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 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; }

16 Using method good() The method good() can be used instead of the method eof(). The method good() can be used instead of the method eof(). // the following program reads lines and displays // them on the screen until the end of the file. #include 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; }

17 Writing to a File Similar to opening for reading, but use ios::out when opening: Similar to opening for reading, but use ios::out when opening: 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;

18 Copying a File to Another File #include 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; }

19 Appending to a File Data can be appended at the end of the file by using ios::app when opening. Data can be appended at the end of the file by using ios::app when opening. Existing data will not be overwritten. Existing data will not be overwritten. myFile.open("data.txt", ios::app);

20 Constant EOF #include 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 and I live in London. data.txt ?y name is ?eorge and ? live in ?ondon. newdata.txt Character denoting the end of file

21 Stream Pointers: get and put All i/o stream objects have, at least, one internal stream pointer: All i/o stream objects have, at least, one internal stream pointer: ifstreams like istream, has a pointer known as get pointer that points to the element to be read in the next input operation. ifstreams like istream, has a pointer known as get pointer that points to the element to be read in the next input operation. ofstreams like ostream, has a pointer known as put pointer that points to the location where the next element will be written. ofstreams like ostream, has a pointer known as put pointer that points to the location where the next element will be written. These internal stream pointers that point to the reading or writing locations within a stream can be manipulated using the following member functions: These internal stream pointers that point to the reading or writing locations within a stream can be manipulated using the following member functions: tellg() and tellp() – These two functions return a value of the member type pos_type, which is an integer data type, representing the current position of the respective pointer. tellg() and tellp() – These two functions return a value of the member type pos_type, which is an integer data type, representing the current position of the respective pointer. seekg(position) and seekp(position) – These functions change the position of the respective pointers. The pointer is changed to the absolute position (counting from the beginning of the file). Parameter position is of member type pos_type (integer). seekg(position) and seekp(position) – These functions change the position of the respective pointers. The pointer is changed to the absolute position (counting from the beginning of the file). Parameter position is of member type pos_type (integer).

22 Stream Pointers #include 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 and I live in London. data.txt My nameand I live in London

23 Overloaded Methods for changing the Stream Pointers There is an overloaded function for both member functions seekg and seekp: There is an overloaded function for both member functions seekg and seekp: directionDescription ios::begoffset counted from the beginning of the stream ios::curoffset counted from the current position of the stream pointer ios::endoffset counted from the end of the stream The position of the get or put pointer is set to an offset value relative to some specific point determined by the parameter direction. Parameter offset is of the member type off_type, which is an integer type and direction is of type seekdir which is an enumerated type that determines the point from where offset is counted from, and that can take any of the following values: The position of the get or put pointer is set to an offset value relative to some specific point determined by the parameter direction. Parameter offset is of the member type off_type, which is an integer type and direction is of type seekdir which is an enumerated type that determines the point from where offset is counted from, and that can take any of the following values: seekg( offset, direction ) seekp( offset, direction )

24 Changing the Stream Pointers Examples CodeDescription 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); long size = myFile.tellg(); cout << ”Size is ” << size << ” bytes”; Display the size of the file:

25 Unget 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 was very happy to go around and see this amazing city data.txt abroad amsterdam and around and amazing Display the words starting with ‘a’: fin.unget();

26 Binary Files In binary files, to input and output data with the extraction and insertion operators ( >) 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 elements (like spaces, newlines, etc.) In binary files, to input and output data with the extraction and insertion operators ( >) 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 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 memory_block is the address of an array of bytes and size is an integer. where memory_block is the address of an array of bytes and size is an integer. read( char* memory_block, int size ) – ifstream, fstream write( char* memory_block, int size ) – ofstream, fstream

27 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(); }

28 Reading Structures from Binary 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

29 Buffers and Synchronization File streams are associated to an internal buffer of type streambuf. This buffer is a memory block that acts as an intermediary between the stream and the physical file. For example, with an ofstream, each time the member function put (which writes a single character) is called, the character is not written directly to the physical file with which the stream is associated. Instead, the character is inserted in the stream’s intermediate buffer. File streams are associated to an internal buffer of type streambuf. This buffer is a memory block that acts as an intermediary between the stream and the physical file. For example, with an ofstream, each time the member function put (which writes a single character) is called, the character is not written directly to the physical file with which the stream is associated. 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 physical medium (if it is an output stream) or freed (if it is an input stream). This process is called synchronization and takes place under the following circumstances: 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). This process is called synchronization and takes place under the following circumstances: When the file is closed: 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 medium. When the file is closed: 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 medium. When the buffer is full: Buffers have a certain size. When the buffer is full it automatically synchronized. When the buffer is full: Buffers have a certain size. When the buffer is full it automatically synchronized. Explicitly, with manipulators: When certain manipulators are used on streams, an explicit synchronization takes place. These manipulators are: flush and endl. Explicitly, with manipulators: When certain manipulators are used on streams, an explicit synchronization takes place. These manipulators are: flush and endl. Explicitly, with member function sync(): calling stream’s member function 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 in the case failure. Otherwise (if successful) it returns 0. Explicitly, with member function sync(): calling stream’s member function 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 in the case failure. Otherwise (if successful) it returns 0.