File I/O in C++ I.

Slides:



Advertisements
Similar presentations
CS 1620 File I/O. So far this semester all input has been from keyboard all output has been to computer screen these are just two examples of where to.
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.
Programming File I/O. COMP102 Prog. Fundamentals File I/O / Slide 2 Copyright © 2000 by Brooks/Cole Publishing Company A division of International Thomson.
File I/O. COMP104 Lecture 20 / Slide 2 Using Input/Output Files * A computer file n is stored on a secondary storage device (e.g., disk) n is permanent.
File I/O. COMP104 Lecture 20 / Slide 2 Using Input/Output Files (Review) * A computer file n is stored secondary storage devices (hard drive, CD) n can.
File I/O. COMP104 File I/O / Slide 2 Using Input/Output Files * A computer file n is stored on a secondary storage device (e.g., disk) n is permanent.
1 10/29/07CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
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.
1 10/25/06CS150 Introduction to Computer Science 1 Reading from and Writing to Files.
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.
Chapter 3: Input/Output
Streams, 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.
Program Input and the Software Design Process ROBERT REAVES.
Stream Handling Streams - means flow of data to and from program variables. - We declare the variables in our C++ for holding data temporarily in the memory.
File I/O ifstreams and ofstreams Sections 11.1 &
1 CS161 Introduction to Computer Science Topic #13.
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.
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.
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.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
Input/Output CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
File Handling in C++.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
Input/Output. Objectives In this chapter you will: Learn what a stream is and examine input and output streams Explore how to use the input stream functions.
File Processing Files are used for data persistance-permanent retention of large amounts of data. Computer store files on secondary storage devices,such.
CS162 External Data Files 1 Today in CS162 External Files What is an external file? How do we save data in a file?
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.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students File Input and Output Checking input for errors.
CS 1430: Programming in C++ 1. File Input in VS Project Properties Debugging Command Arguments quiz8-1.out We want to know how to do it ourselves, right?
1 Stream Input and Output Read Text, page Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) KeyboardScreen executing.
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Chapter Eight: Streams Slides by Evan Gallagher.
Programming II I/O Streams and Data Files 1(c) Asma AlOsaimi.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
Introduction Every program takes some data as input and generate processed data as out put . It is important to know how to provide the input data and.
CS212: Object Oriented Analysis and Design
Chapter 14: Sequential Access Files
ifstreams and ofstreams
File Processing in C++ Data is stored in files so that it may be retrieved for processing when needed.
CS-103 COMPUTER PROGRAMMING
Tutorial4us.com File Handling in C++ Tutorial4us.com.
Lecture 9 Files, Pointers
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.
Lab 7: File Input/Output Graham Northup
Copyright © 2003 Pearson Education, Inc.
Review of Strings which include file needs to be used for string manipulation? what using statement needs to be included fro string manipulation? how is.
FILE INPUT OUTPUT Skill Area 315 Part B Materials Prepared by
File I/O.
Basic File I/O and Stream Objects
Programming with Data Files
when need to keep permanently
Text Files All the programs you've seen so far have one thing in common: Any data the program uses or calculates is lost when the program ends. In order.
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.
Standard Input/Output Stream
File Processing in C++ Data is stored in files so that it may be retrieved for processing when needed.
File I/O.
File I/O in C++ I.
File I/O.
CPS120: Introduction to Computer Science
CHAPTER 4 File Processing.
Reading from and Writing to Files
Reading Data From and Writing Data To Text Files
ifstreams and ofstreams
File I/O in C++ II.
Lecture 9 Files Handling
Reading from and Writing to Files
Presentation transcript:

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 input data to a program or receive output data from a program or both; should reside in Project directory for easy access; must be opened before it is used.

General File I/O Steps Include the header file fstream in the program. Declare file stream variables. Associate the file stream variables with the input/output sources. Open the file Use the file stream variables with >>, <<, or other input/output functions. Close the files.

Classes for Stream I/O in C++ ios is the base class. istream and ostream inherit from ios ifstream inherits from istream (and ios) ofstream inherits from ostream (and ios) iostream inherits from istream and ostream (& ios) fstream inherits from ifstream, iostream, and ofstream

STEP1 : Include the header file stream - a sequence of characters interactive (iostream)  cin - input stream associated with keyboard. cout - output stream associated with display file (fstream)  ifstream - defines new input stream (normally associated with a file).  ofstream - defines new output stream (normally associated with a file). #include <fstream>

STEP2 : Declare file stream variables. ifstream fIn; //input ofstream fOut; // output fstream both //input & output

STEP3 : Associate the file stream variables with the input/output sources. One way is to do it like this : ifstream fIn(“file1.txt”); // input ofstream fOut(“file2,txt”); // output fstream both (“file3.txt”); //input & output

STEP4 : Open the file In the case of an input file: Opening a file associates a file stream variable declared in the program with a physical file at the source, such as a disk. In the case of an input file: the file must exist before the open statement executes. If the file does not exist, the open statement fails and the input stream enters the fail state In the case of an output file: An output file does not have to exist before it is opened; if the output file does not exist, the computer prepares an empty file for output. If the designated output file already exists, by default, the old contents are erased when the file is opened.

Object and Member Functions open() Name Stream handle Name both.open("numbers.txt“) File Name Dir:\\folder\fileName.extention Extention ( .dat, .out, .txt) Dot Operator Calling Object

Validate the file before trying to access First method Second method By checking the stream variable; If ( ! both) {Cout << “Cannot open file”;} By using bool is_open() function. If ( !both.is_open()) {Cout << “File is not open.”;}

File I/O Example: Open output file with validation #include <fstream> using namespace std; void main() { // declear output file variable ofstream outFile; // open an exist file fout.txt outFile.open(“fout.txt”); // Open validation if(! outFile.is_open() ) { Cout << “Cannot open file.\n ”;} } This program will create the file fout.txt in the directory from where you are executing it, and will put “Hello, world!” into it. Here is what every line means: #include <fstream> - You need to include this file in order to use C++’s functions for File I/O. In this file, are declared several classes, including ifstream, ofstream and fstream, which are all derived from istream and ostream. ofstream outFile(“cpp-home.txt”); ofstream means “output file stream”. It creates a handle for a stream to write in a file. outFile – that’s the name of the handle. You can pick whatever you want! (“fout.txt”); - opens the file fout.txt, which should be placed in the directory from where you execute the program. If such a file does not exists, it will be created for you, so you don’t need to worry about that! Now, let’s look a bit deeper. First, I’d like to mention that ofstream is a class. So, ofstream outFile(“fout.txt”); creates an object from this class. What we pass in the brackets, as parameter, is actually what we pass to the constructor. It is the name of the file. So, to summarize: we create an object from class ofstream, and we pass the name of the file we want to create, as an argument to the class’ constructor. There are other things, too, that we can pass, but I will look into that, later. outFile<< “Hello World,!”; - “<<” looks familiar? Yes, you’ve seen it in cout <<. This (“<<”) is a predefined operator. Anyway, what this line makes, is to put the text above in the file. As mentioned before, outFile is a handle to the opened file stream. So, we write the handle name, << and after it we write the text in inverted commas. If we want to pass variables instead of text in inverted commas, just pass it as a regular use of the cout <<. This way: outFile << variablename; That’s it! outFile.close(); - As we have opened the stream, when we finish using it, we have to close it. outFile is an object from class ofstream, and this class (ofstream) has a function that closes the stream. That is the close() function. So, we just write the name of the handle, dot and close(), in order to close the file stream! Notice: Once you have closed the file, you can’t access it anymore, until you open it again.

STEP5: use the file stream STEP6: close the file File I/O Example: Writing #include <fstream> using namespace std; void main() { /* declear and automaticaly open the file*/ ofstream outFile(“fout.txt"); //behave just like cout, put the word into the file outFile << "Hello World!"; outFile.close(); } This program will create the file fout.txt in the directory from where you are executing it, and will put “Hello, world!” into it. Here is what every line means: #include <fstream> - You need to include this file in order to use C++’s functions for File I/O. In this file, are declared several classes, including ifstream, ofstream and fstream, which are all derived from istream and ostream. ofstream outFile(“cpp-home.txt”); ofstream means “output file stream”. It creates a handle for a stream to write in a file. outFile – that’s the name of the handle. You can pick whatever you want! (“fout.txt”); - opens the file fout.txt, which should be placed in the directory from where you execute the program. If such a file does not exists, it will be created for you, so you don’t need to worry about that! Now, let’s look a bit deeper. First, I’d like to mention that ofstream is a class. So, ofstream outFile(“fout.txt”); creates an object from this class. What we pass in the brackets, as parameter, is actually what we pass to the constructor. It is the name of the file. So, to summarize: we create an object from class ofstream, and we pass the name of the file we want to create, as an argument to the class’ constructor. There are other things, too, that we can pass, but I will look into that, later. outFile<< “Hello World,!”; - “<<” looks familiar? Yes, you’ve seen it in cout <<. This (“<<”) is a predefined operator. Anyway, what this line makes, is to put the text above in the file. As mentioned before, outFile is a handle to the opened file stream. So, we write the handle name, << and after it we write the text in inverted commas. If we want to pass variables instead of text in inverted commas, just pass it as a regular use of the cout <<. This way: outFile << variablename; That’s it! outFile.close(); - As we have opened the stream, when we finish using it, we have to close it. outFile is an object from class ofstream, and this class (ofstream) has a function that closes the stream. That is the close() function. So, we just write the name of the handle, dot and close(), in order to close the file stream! Notice: Once you have closed the file, you can’t access it anymore, until you open it again.

STEP5: use the file stream STEP6: close the file File I/O Example: Writing #include <fstream> using namespace std; Void main() { // declear output file variable ofstream outFile; // open an exist file fout.txt outFile.open(“fout.txt”); //behave just like cout, put the word into the file outFile << "Hello World!"; outFile.close(); } This program will create the file fout.txt in the directory from where you are executing it, and will put “Hello, world!” into it. Here is what every line means: #include <fstream> - You need to include this file in order to use C++’s functions for File I/O. In this file, are declared several classes, including ifstream, ofstream and fstream, which are all derived from istream and ostream. ofstream outFile(“cpp-home.txt”); ofstream means “output file stream”. It creates a handle for a stream to write in a file. outFile – that’s the name of the handle. You can pick whatever you want! (“fout.txt”); - opens the file fout.txt, which should be placed in the directory from where you execute the program. If such a file does not exists, it will be created for you, so you don’t need to worry about that! Now, let’s look a bit deeper. First, I’d like to mention that ofstream is a class. So, ofstream outFile(“fout.txt”); creates an object from this class. What we pass in the brackets, as parameter, is actually what we pass to the constructor. It is the name of the file. So, to summarize: we create an object from class ofstream, and we pass the name of the file we want to create, as an argument to the class’ constructor. There are other things, too, that we can pass, but I will look into that, later. outFile<< “Hello World,!”; - “<<” looks familiar? Yes, you’ve seen it in cout <<. This (“<<”) is a predefined operator. Anyway, what this line makes, is to put the text above in the file. As mentioned before, outFile is a handle to the opened file stream. So, we write the handle name, << and after it we write the text in inverted commas. If we want to pass variables instead of text in inverted commas, just pass it as a regular use of the cout <<. This way: outFile << variablename; That’s it! outFile.close(); - As we have opened the stream, when we finish using it, we have to close it. outFile is an object from class ofstream, and this class (ofstream) has a function that closes the stream. That is the close() function. So, we just write the name of the handle, dot and close(), in order to close the file stream! Notice: Once you have closed the file, you can’t access it anymore, until you open it again.

File I/O Example: Reading Read char by char #include <iostream> #include <fstream> void main() { //Declare and open a text file ifstream INFile(“data.txt"); char ch; //do until the end of file while( ! INFile.eof() ) { INFile.get(ch); // get one character cout << ch; // display the character } INFile.close(); // close the file

Read line by line File I/O Example: Reading #include <iostream> #include <fstream> #include <string> int main() { //Declare and open a text file ifstream INFile(“data.txt"); string line; while(! INFile.eof()) {/fetch line from data.txt and put it in a string getline(INFile, line); cout << line; } INFile.close(); // close the file

Example writing to file #include <iostream> #include <fstream> using namespace std; void main() { ofstream outFile; // open an exist file fout.txt outFile.open("number.txt",ios::app); if (!outFile.is_open()) { cout << " problem with opening the file ";} else {outFile <<200 <<endl ; cout << "done writing" <<endl;} outFile.close(); }

Example Reading from file #include <iostream> #include <fstream> #include <string> #include <sstream> using namespace std; void main() {//Declare and open a text file ifstream INFile("number.txt"); string line; int total=0; while(! INFile.eof()) {//fetch line from number.txt and put it in a string getline(INFile, line); //converting line string to int stringstream(line) >> total; cout << line <<endl; cout <<total +1<<endl;} INFile.close(); // close the file }