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.

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

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.
© 2000 Scott S Albert Structured Programming 256 Chapter 7 Streams and 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 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.
C++ plus. 2 Goals Some general C++ tips 3 C++ Tips is header file for a library that defines three stream objects Keyboard an istream object named cin.
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.
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.
Programming File I/O. COMP102 Prog. Fundamentals File I/O / Slide 2 Copyright © 2000 by Brooks/Cole Publishing Company A division of International Thomson.
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.
File I/O ifstreams and ofstreams Sections 11.1 &
Chapter 9 I/O Streams and Data Files
1 CS161 Introduction to Computer Science Topic #13.
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.
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.
C++ Programming: chapter 6 – iostream 2014, Spring Pusan National University Ki-Joune Li 1.
COMP102 Lab 071 COMP 102 Programming Fundamentals I Presented by : Timture Choi.
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
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.
C++ Programming: chapter 6 – iostream 2015, Spring Pusan National University Ki-Joune Li 1.
Learners Support Publications Working with Files.
CS162 External Data Files 1 Today in CS162 External Files What is an external file? How do we save data in a file?
Lecture 14 Arguments, Classes and Files. Arguments.
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.
File I/O. Files allow permanent storage of programs and data. ifstream and ofstream objects –For file I/O the inclusion of is required. –Objects for file.
1 Stream Input and Output Read Text, page Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) KeyboardScreen executing.
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
ifstreams and ofstreams
File Processing in C++ Data is stored in files so that it may be retrieved for processing when needed.
Chapter 8 (Part 3) Library Classes for Strings (P.405)
CS-103 COMPUTER PROGRAMMING
Auburn University COMP 3000 Object-Oriented Programming for Engineers and Scientists File I/O Dr. Xiao Qin Auburn University.
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.
COMP 2710 Software Construction File I/O
Copyright © 2003 Pearson Education, Inc.
FILE INPUT OUTPUT Skill Area 315 Part B Materials Prepared by
File I/O.
Programming with Data Files
when need to keep permanently
Review of Strings which include file needs to be used for string manipulation? what using statement needs to be included for string manipulation? how is.
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.
Programming 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
File I/O in C++ I.
Reading from and Writing to Files
Presentation transcript:

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 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 1.Include the header file fstream in the program. 2.Declare file stream variables. 3.Associate the file stream variables with the input/output sources. 4.Open the file 5.Use the file stream variables with >>, <<, or other input/output functions. 6.Close the file.

Using Input/Output Files  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).

Stream I/O Library Header Files  Note: There is no “.h” on standard header files :  iostream -- contains basic information required for all stream I/O operations  fstream -- contains information for performing file I/O operations

C++ streams //Add additional header files you use #include int main () { /* Declare file stream variables such as the following */ ifstream fsIn;//input ofstream fsOut; // output fstream both //input & output //Open the files fsIn.open("prog1.txt"); //open the input file fsOut.open("prog2.txt"); //open the output file //Code for data manipulation. //Close files fsIn.close(); fsOut.close(); return 0; }

Object and Member Functions input_stream.open("numbers.txt“)

Open()  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  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.

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

File I/O Example: Open the file with validation First Method (use the constructor )Second Method ( use Open function) #include using namespace std; int main() { //declare and automatically open the file ofstream outFile(“fout.txt"); // Open validation if(! outFile) { Cout << “Cannot open file.\n ”; return 1; } return 0; } #include using namespace std; int main() { //declare 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 ”; return 1; } return 0; }

More Input File-Related Functions  ifstream fsin;  fsin.open(const char[] fname)  connects stream fsin to the external file fname.  fsin.get(char character)  extracts next character from the input stream fsin and places it in the character variable character.  fsin.eof()  tests for the end-of-file condition.

File I/O Example: Reading Read char by charRead a line #include int main() {//Declare and open a text file ifstream openFile(“data.txt"); char ch; //do until the end of file while( ! OpenFile.eof() ) { OpenFile.get(ch); // get one character cout << ch; // display the character } OpenFile.close(); // close the file return 0; } #include int main() {//Declare and open a text file ifstream openFile("data.txt"); string line; while(!openFile.eof()) {//fetch line from data.txt and put it in a string getline(openFile, line); cout << line; } openFile.close(); // close the file return 0; }

More Output File-Related Functions  ofstream fsOut;  fsOut.open(const char[] fname)  connects stream fsOut to the external file fname.  fsOut.put(char character)  inserts character character to the output stream fsOut.  fsOut.eof()  tests for the end-of-file condition.

File I/O Example: Writing First Method (use the constructor) Second Method ( use Open function) #include using namespace std; int main() {/* declare and automatically open the file*/ ofstream outFile("fout.txt"); //behave just like cout, put the word into the file outFile << "Hello World!"; outFile.close(); return 0; } #include using namespace std; int main() {// declare 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(); return 0; }

File Open Mode NameDescription ios::inOpen file to read ios::outOpen file to write ios::appAll the data you write, is put at the end of the file. It calls ios::out ios::ateAll the data you write, is put at the end of the file. It does not call ios::out ios::truncDeletes all previous content in the file. (empties the file) ios::nocreateIf the file does not exists, opening it with the open() function gets impossible. ios::noreplaceIf the file exists, trying to open it with the open() function, returns an error. ios::binaryOpens the file in binary mode.

File Open Mode #include int main(void) { ofstream outFile("file1.txt", ios::out); outFile << "That's new!\n"; outFile.close(); Return 0; } If you want to set more than one open mode, just use the OR operator- |. This way: ios::ate | ios::binary

Summary of Input File-Related Functions #include ifstream fsIn;  fsIn.open(const char[] fname)  connects stream fsIn to the external file fname.  fsIn.get(char& c)  extracts next character from the input stream fsIn and places it in the character variable c.  fsIn.eof()  tests for the end-of-file condition.  fsIn.close()  disconnects the stream and associated file.  fsIn >> c; //Behaves just like cin

Summary of Output File-Related Functions #include ofstream fsOut;  fsOut.open(const char[] fname)  connects stream fsOut to the external file fname.  fsOut.put(char c)  inserts character c to the output stream fsOut.  fsOut.eof()  tests for the end-of-file condition.  fsOut.close()  disconnects the stream and associated file.  fsOut << c; //Behaves just like cout

File format  In c++ files we (read from/ write to) them as a stream of characters  What if I want to write or read numbers ?

Example writing to file #include 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 using namespace std; void main() {//Declare and open a text file ifstream INFile("number.txt"); string line; int total=0; while(! INFile.eof()) { getline(INFile, line); //converting line string to int stringstream(line) >> total; cout << line <<endl; cout <<total +1<<endl;} INFile.close(); // close the file }