File input and output in C++ Dr. Ahmed Telba. CSE202: Lecture 9The Ohio State University2 Reading & Writing to Files.

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.
File I/O Finished off Colin Cherry standing in for Dr. Lin.
1 11/3/08CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
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.
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.
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.
Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output.
Darbas su failais Arnas Terekas IT 1gr. Vilniaus universitetas Matematikos ir informatikos fakultetas.
Chapter 8 Data File Basics.
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 &
1 CS161 Introduction to Computer Science Topic #13.
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 Input and Output in C++. Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) Keyboard Screen executing program input data.
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.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
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.
TEXT FILES. CIN / COUT REVIEW  We are able to read data from the same line or multiple lines during successive calls.  Remember that the extraction.
Computer Programming TCP1224 Chapter 13 Sequential File Access.
C++ FILE I/O.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT11: File I/O CS2311 Computer Programming.
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.
Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba.
Loops and Files. 5.1 The Increment and Decrement Operators.
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.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 6 I/O Streams as an Introduction to Objects and Classes.
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.
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.
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.
Writing to Files and Reading From Files. Writing Data to a File Creating a new file, a.dat or.txt file #include #include // for file writing #include.
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.
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.
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Chapter Eight: Streams Slides by Evan Gallagher.
CS212: Object Oriented Analysis and Design
Chapter 14: Sequential Access Files
What is wrong in the following function definition
ifstreams and ofstreams
Basic file operations 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.
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
Lecture 5A File processing Richard Gesick.
Basic File I/O and Stream Objects
Today’s Lecture I/O Streams Tools for File I/O
when need to keep permanently
CSC 143 Stream I/O Classes and Files [A11-A15, A38-A50]
File I/O in C++ I.
CPS120: Introduction to Computer Science
C++ Programming: chapter 6 – iostream
Reading from and Writing to Files
ifstreams and ofstreams
File I/O in C++ I.
Reading from and Writing to Files
Input/Output Streams, Part 2
Text Files.
Presentation transcript:

File input and output in C++ Dr. Ahmed Telba

CSE202: Lecture 9The Ohio State University2 Reading & Writing to Files

CSE202: Lecture 9The Ohio State University3 helloworld.cpp #include using namespace std; int main() { cout << "Hello World!" << endl; cout << "Goodbye World!" << endl; return 0; }

CSE202: Lecture 9The Ohio State University4 helloworld.cpp #include using namespace std; int main() { cout << "Hello World!" << endl; cout << "Goodbye World!" << endl; return 0; } > helloworld.output Hello World! Goodbye World! >

CSE202: Lecture 9The Ohio State University5 Writing to Files

CSE202: Lecture 9The Ohio State University6 I/O File Streams A File Stream is a one-way transmission path used to connect a file stored on a physical device (disk, CD- ROM, etc) to a program. Two directions: – Input File Stream (read from a file) – Output File Stream (write to a file) To use file stream operations we #include

CSE202: Lecture 9The Ohio State University7 Writing to Files: Output File Stream To write a file: 1.Create an output stream object 2.Establish connection to a file 3.Check Validity 4.Start writing 5.Close the file

CSE202: Lecture 9The Ohio State University8 writeFile1.cpp #include // function exit() is in cstdlib #include // class ofstream() is in fstream #include using namespace std; int main() { ofstream fout; // declare an output file stream fout.open("hellofile.txt", ios::out); // open file file_name for output if (!fout.is_open()) // check if file is opened for output { cerr << "Unable to open file hellofile.txt." << endl; exit(10); }

CSE202: Lecture 9The Ohio State University9 writeFile1.cpp (cont) cout << "Writing to file hellofile.txt." << endl; // write text to the file fout << "Hello World!" << endl; fout << "Goodbye World!" << endl; // close file stream fout fout.close(); return 0; }

CSE202: Lecture 9The Ohio State University10 Writing to Files (1) 1.“Create an output stream object” – Make sure we included the class. – Create a variable of type ofstream. For example, ofstream fout; – The fout variable is what we would also call an “output file handler”

CSE202: Lecture 9The Ohio State University11 Writing to Files (2) 2.“Establish a connection to a file” – Open the file “hellofile.txt” for output: fout.open(“hellofile.txt”, ios::out);

CSE202: Lecture 9The Ohio State University12 Writing to Files (3) 3.“Check Validity” – Many things can prevent our file from being opened. – For instance, we may not have permission to write to hellofile.txt. These runtime errors must be handled before we do any writing! if (!fout.is_open()) // check if file is open { cerr << "Unable to open file hellofile.txt." << endl; exit(10); }

CSE202: Lecture 9The Ohio State University13 Writing to Files (3) 3.“Check Validity” (continued…) – In the previous code, exit() is a function that terminates program execution. – So, why not just use return 0; as we have been all this time to indicate termination of main() ? We could have, but exit() actually performs some routine maintenance before termination (including file stream cleanup). – To use exit() we must first #include

CSE202: Lecture 9The Ohio State University14 Writing to Files (4) 4.“Start writing” – Now that we are certain our file handler, fout, is valid we can start writing to the file that is associated with it. – This should look familiar... fout << “Hello World” << endl; – This will print “Hello World” to hellofile.txt

CSE202: Lecture 9The Ohio State University15 Writing to Files (5) 5.“Close the file” – After we are finished writing to our file, it is always important to close the file: fout.close(); – Why is this a good idea? Can now reuse fout handler for other file writes If we are not careful, our program could be keeping many files open… which can lead to very bad things.

CSE202: Lecture 9The Ohio State University16 Formatted Writing to Files – Notice the similarities between cout and fout. – In fact, everything we can do with cout also applies to fout. Including I/O manipulation: setprecision(), setw(), etc. – Though we named our file handler fout to strike name similarities with cout, we could have actually named it anything arbitrary (just like other variables).

CSE202: Lecture 9The Ohio State University17 writeFile2.cpp #include // function exit() is in cstdlib #include // class ofstream() is in fstream #include using namespace std; int main() { ofstream fout; // declare an output file stream fout.open("sample.txt", ios::out); // open file file_name for output if (!fout.is_open()) // check if file is opened for output { cerr << "Unable to open file sample.txt." << endl; exit(10); }

CSE202: Lecture 9The Ohio State University18 writeFile2.cpp (cont) cout << "Writing to file sample.txt." << endl; // write to the file fout << "Test file output." << endl; fout << "100.0/3.0 = " << 100.0/3.0 << endl; fout.precision(12); fout << "100.0/3.0 = " << 100.0/3.0 << endl; fout << "100.0/3.0 = " << fixed << 100.0/3.0 << endl; // close file stream fout fout.close(); return 0; }

CSE202: Lecture 9The Ohio State University19 writeMultiFile.cpp... ofstream fout1; // declare output file stream 1 ofstream fout2; // declare output file stream 2 fout1.open("book1.txt", ios::out); // open book1.txt fout2.open("book2.txt", ios::out); // open book2.txt if (!fout1.is_open()) { cerr << "Unable to open file book1.txt." << endl; exit(10); } if (!fout2.is_open()) { cerr << "Unable to open file book2.txt." << endl; exit(15); }

CSE202: Lecture 9The Ohio State University20 writeMultiFile.cpp (cont) cout << "Writing to files book1.txt and book2.txt." << endl; // write to book1.txt fout1 << "Assets: $" << << endl; fout1 << "Liabilities: $" << << endl; // write to book2.txt fout2 << "Assets: $" << << endl; fout2 << "Liabilities: $" << 9000 << endl; fout1.close(); // close file stream fout1 fout2.close(); // close file stream fout2 return 0; }

CSE202: Lecture 9The Ohio State University21 Asking for the File Name Read the input file name into a string: #include string file_name; cout << “Enter file name: “; cin >> file_name; Unfortunately, the open() function only takes C style strings. Convert a C++ string into a C style string: file_name.c_str(); Call fout.open() using the C style string: fout.open(file_name.c_str(), ios::out);

CSE202: Lecture 9The Ohio State University22 writeFile3.cpp... #include #include // type string is in file “string”... int main() { ofstream fout; // declare an output file stream string file_name; cout << "Enter file name: "; cin >> file_name; // file_name.c_str() returns a C style string fout.open(file_name.c_str(), ios::out); // open file file_name for output if (!fout.is_open()) // check if file is opened for output { cerr << "Unable to open file " << file_name << endl; exit(10); }

CSE202: Lecture 9The Ohio State University23 writeFile3.cpp (cont) cout << "Writing to file " << file_name << endl; // write text to the file fout << "Hello World!" << endl; fout << "Goodbye World!" << endl; // close file stream fout fout.close(); return 0; }

CSE202: Lecture 9The Ohio State University24 Reading from Files

CSE202: Lecture 9The Ohio State University25 Reading from Files: Input File Stream To read from a file: 1.We need a-priori knowledge of the file format 2.Create an input stream object 3.Establish connection to a file 4.Check Validity 5.Start reading 6.Close the file

CSE202: Lecture 9The Ohio State University26 readFile1.cpp #include // function exit() is in cstdlib #include // class ofstream() is in fstream #include using namespace std; int main() { ifstream fin; // declare an input file stream int x; fin.open("intList1.txt", ios::in); // open file intList.txt for input if (!fin.is_open()) // check if file is open for input { cerr << "Unable to open file intList1.txt." << endl; exit(10); }...

CSE202: Lecture 9The Ohio State University27 readFile1.cpp (cont) // read text from file fin >> x; cout << "Read integer: " << x << endl; // close file stream fin fin.close(); return 0; }

CSE202: Lecture 9The Ohio State University28 > readFile1.exe Read integer: 77 > … // read text from file fin >> x; cout << "Read integer: " << x << endl; … File: intList1.txt

CSE202: Lecture 9The Ohio State University29 Reading from Files (1) 1.“Have prior knowledge of file format” – Does the input file contain integers, floating point numbers, or strings? – Files can be some combination of different types, e.g.: 523 Warren Harding William McKinley 3.21 … – For each row, the first item is an integer, the second is a string, the third is a string, and the last is a double.

CSE202: Lecture 9The Ohio State University30 Reading from Files (2) 2. “Create an input stream object” – Again, make sure we included the class. – Create a variable of type ifstream. For example, ifstream fin; – The fin variable is what we would also call an “input file handler”

CSE202: Lecture 9The Ohio State University31 Reading from Files (3) 3. “Establish a connection to a file” – Open the file “intList1.txt”: fin.open(“intList1.txt”, ios::in);

CSE202: Lecture 9The Ohio State University32 Reading from Files (4) 4. “Check Validity” – Again, we should check that the file is able to be opened and read. // check if file is open for input if (!fin.is_open()) { cerr << "Unable to open file " << file_name << endl; exit(10); }

CSE202: Lecture 9The Ohio State University33 Reading from Files (5) 5. “Start reading” – Because we know that the file contains integers, we read the data into a variable of type int : int x; // read text from file fin >> x;

CSE202: Lecture 9The Ohio State University34 Reading from Files (6) 6. “Close the file” – Like before, we close the file after we are done using it: fin.close();

CSE202: Lecture 9The Ohio State University35 readFile2.cpp... #include... int main() { ifstream fin; // declare an input file stream string file_name; int x; cout << "Enter file name: "; cin >> file_name; fin.open(file_name.c_str(), ios::in); // open file file_name for input if (!fin.is_open()) // check if file is open for input { cerr << "Unable to open file " << file_name << endl; exit(10); }

CSE202: Lecture 9The Ohio State University36 readFile2.cpp (cont) // read text from file for (int i = 1; i <= 5; i++) { fin >> x; cout << "Read integer: " << x << endl; } // close file stream fin fin.close(); return 0; }

CSE202: Lecture 9The Ohio State University37 > readFile2.exe Enter file name: intList1.txt Read integer: 77 Read integer: 65 Read integer: 28 Read integer: 33 Read integer: 112 > … // read text from file for (int i = 1; i <= 5; i++) { fin >> x; cout << "Read integer: " << x << endl; } … File: intList1.txt

CSE202: Lecture 9The Ohio State University38 > readFile2.exe Enter file name: missing.txt Unable to open file missing.txt > … if (!fin.is_open()) // check if file is open for input { cerr << "Unable to open file " << file_name << endl; exit(10); } …

CSE202: Lecture 9The Ohio State University39 > readFile2.exe Enter file name: intList2.txt Read integer: 10 Read integer: 20 > … // read text from file for (int i = 1; i <= 5; i++) { fin >> x; cout << "Read integer: " << x << endl; } … File: intList3.txt 10 20

CSE202: Lecture 9The Ohio State University40 readFile3.cpp... int main() { ifstream fin; // declare an input file stream string file_name; int x; cout << "Enter file name: "; cin >> file_name; fin.open(file_name.c_str(), ios::in); // open file file_name for input if (!fin.is_open()) // check if file is open for input { cerr << "Unable to open file " << file_name << endl; exit(10); }

CSE202: Lecture 9The Ohio State University41 readFile3.cpp (cont) // read text from file fin >> x; while (!fin.fail()) { cout << "Read integer: " << x << endl; fin >> x; } // close file stream fin fin.close(); return 0; }

CSE202: Lecture 9The Ohio State University42 fail() The fail() function is true when the read fails. A read fails because: – The end of file is reached. – Read error: Trying to read a character string as an integer. Once an input operation fails, all subsequent input operations will fail.

CSE202: Lecture 9The Ohio State University43 fail() To read all integers in a file: fin >> x; while (!fin.fail()) { // Process x... fin >> x; }

CSE202: Lecture 9The Ohio State University44 > readFile3.exe Enter file name: intList1.txt Read integer: 77 Read integer: 65 Read integer: 28 Read integer: 33 Read integer: 112 > … // read text from file fin >> x; while (!fin.fail()) { cout << "Read integer: " << x << endl; fin >> x; } … File: intList1.txt

CSE202: Lecture 9The Ohio State University45 > readFile3.exe Enter file name: intList2.txt Read integer: 10 Read integer: 20 Read integer: 30 Read integer: 40 Read integer: 50 Read integer: 60 Read integer: 70 > … // read text from file fin >> x; while (!fin.fail()) { cout << "Read integer: " << x << endl; fin >> x; } … File: intList1.txt

CSE202: Lecture 9The Ohio State University46 > readFile3.exe Enter file name: intList3.txt Read integer: 10 Read integer: 20 > … // read text from file fin >> x; while (!fin.fail()) { cout << "Read integer: " << x << endl; fin >> x; } … File: intList3.txt 10 20

CSE202: Lecture 9The Ohio State University47 readFile4.cpp... int main() { ifstream fin; // declare an input file stream string file_name; int x; cout << "Enter file name: "; cin >> file_name; fin.open(file_name.c_str(), ios::in); // open file file_name for input if (!fin.is_open()) // check if file is open for input { cerr << "Unable to open file " << file_name << endl; exit(10); }

CSE202: Lecture 9The Ohio State University48 readFile4.cpp (cont) // read text from file fin >> x; while (fin) // equivalent to while (!fin.fail()) { cout << "Read integer: " << x << endl; fin >> x; } // close file stream fin fin.close(); return 0; }

CSE202: Lecture 9The Ohio State University49 fail() ifstream fin; The condition: while(fin) is equivalent to: while(!fin.fail())

CSE202: Lecture 9The Ohio State University50 fail() The fail() function is true when the read fails. A read fails because: – The end of file is reached. – Read error: Trying to read a character string as an integer. Once an input operation fails, all subsequent input operations will fail.

CSE202: Lecture 9The Ohio State University51 … // read text from file fin >> x; while (!fin.fail()) { cout << "Read integer: " << x << endl; fin >> x; } … File: intListBad.txt Hello What happens when readfFile3.exe is run on file intListBad.txt ?

CSE202: Lecture 9The Ohio State University52 eof(): End of File The eof() function is true when the function reaches the end of file.

CSE202: Lecture 9The Ohio State University53 readFile5.cpp... int main() { ifstream fin; // declare an input file stream string file_name; int x; cout << "Enter file name: "; cin >> file_name; fin.open(file_name.c_str(), ios::in); // open file file_name for input if (!fin.is_open()) // check if file is open for input { cerr << "Unable to open file " << file_name << endl; exit(10); }

CSE202: Lecture 9The Ohio State University54 readFile5.cpp (cont) fin >> x;// read text from file while (!fin.fail()) { cout << "Read integer: " << x << endl; fin >> x; } if (!fin.eof())// check for error { cerr << "Error reading file " << file_name << endl; exit(20); } fin.close();// close file stream fin return 0; }

CSE202: Lecture 9The Ohio State University55 eof() and fail() The fail() function is true when the read fails. A read fails because: – The end of file is reached. – Read error: Trying to read a character string as an integer. To check for a read error: if (!fin.eof())// check for error { cerr << "Error reading file " << file_name << endl; exit(20); }

CSE202: Lecture 9The Ohio State University56 eof() and fail() To check for a read error: if (!fin.eof())// check for error { cerr << "Error reading file " << file_name << endl; exit(20); } Use cerr instead of cout for printing error messages. Use exit(20) to exit the program on an error and return code integer 20.

CSE202: Lecture 9The Ohio State University57 > readFile5.exe Enter file name: intListBad.txt Read integer: 77 Read integer: 65 Read integer: 28 Error reading file intListBad.txt > … if (!fin.eof())// check for error { cerr << "Error reading file " << file_name << endl; exit(20); } … File: intListBad.txt Hello

CSE202: Lecture 9The Ohio State University58 Common Errors Writing to a file which was opened for reading; Reading from a file which was opened for writing; Forgetting to open a file; Not checking for read failure.

Class in file All these flags can be combined using the bitwise operator OR (|). For example, if we want to open the fileexample.bin in binary mode to add data we could do it by the following call to member function open(): ofstream myfile; myfile.open ("example.bin", ios::out | ios::app | ios::binary);

File in c++ ofstream fout ; fout.open("file path",iostream family); fout<<"data";

Basic file operations in C++ #include using namespace std; int main () { ofstream myfile; myfile.open ("example22.txt"); myfile << "Writing this to a file.\n"; myfile.close(); system("pause"); return 0; }

// writing on a text file #include using namespace std; int main () { ofstream myfile ("example.txt"); if (myfile.is_open()) { myfile << "This is a line.\n"; myfile << "This is another line.\n"; myfile.close(); } else cout << "Unable to open file"; return 0; }

// reading a text file #include using namespace std; int main () { string line; ifstream myfile ("example.txt"); if (myfile.is_open()) { while ( myfile.good() ) { getline (myfile,line); cout << line << endl; } myfile.close(); } else cout << "Unable to open file"; return 0; }

// reading a text file #include using namespace std; int main () { char buffer[256]; ifstream examplefile ("example.txt"); if (! examplefile.is_open()) { cout << "Error opening file"; exit (1); } while (! examplefile.eof() ) { examplefile.getline (buffer,100); cout << buffer << endl; } return 0; }

Checking state flags In addition to good(), which checks whether the stream is ready for input/output operations, other member functions exist to check for specific states of a stream (all of them return a bool value): bad()Returns true if a reading or writing operation fails. For example in the case that we try to write to a file that is not open for writing or if the device where we try to write has no space left. fail()Returns true in the same cases as bad(), but also in the case that a format error happens, like when an alphabetical character is extracted when we are trying to read an integer number. eof()Returns true if a file open for reading 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. In order to reset the state flags checked by any of these member functions we have just seen we can use the member function clear(), which takes no parameters.

// obtaining file size #include using namespace std; int main () { long begin,end; ifstream myfile ("example.txt"); begin = myfile.tellg(); myfile.seekg (0, ios::end); end = myfile.tellg(); myfile.close(); cout << "size is: " << (end-begin) << " bytes.\n"; return 0; }

Binary files In binary files, to input and output data with the extraction and insertion operators ( >) and functions like getline is not efficient, since we do not need to format any data, and data may not use the separation codes used by text files to separate elements (like space, newline, etc...). File streams include two member functions specifically designed to input and output binary data sequentially: writeand read. The first one (write) is a member function of ostream inherited by ofstream. And read is a member function of istream that is inherited by ifstream. Objects of class fstream have both members. Their prototypes are: write ( memory_block, size ); read ( memory_block, size ); Where memory_block is of type "pointer to char" (char*), and represents the address of an array of bytes where the read data elements are stored or from where the data elements to be written are taken. The size parameter is an integer value that specifies the number of characters to be read or written from/to the memory block.

/ reading a complete binary file #include using namespace std; ifstream::pos_type size; char * memblock; int main () { ifstream file ("example.bin", ios::in|ios::binary|ios::ate); if (file.is_open()) { size = file.tellg(); memblock = new char [size]; file.seekg (0, ios::beg); file.read (memblock, size); file.close(); cout << "the complete file content is in memory"; delete[] memblock; } else cout << "Unable to open file"; return 0; }

Write in file #include using namespace std; int main () { { ofstream fout; fout.open("D:\\firstExa.txt"); // fout.open("firstExa.txt"); fout << "HELLOW MOHMED AH-ROB.\n" << "WELCOME YOU PROGRAM\n" << "WHAT DA YOU LIKE OF ME\n"; fout.close(); system("pause"); return 0; }

// output file #include using namespace std; int main() { ifstream myReadFile; myReadFile.open("text.txt"); char output[100]; if (myReadFile.is_open()) { while (!myReadFile.eof()) { myReadFile >> output; cout<<output; } myReadFile.close(); system("pause"); return 0; }

#include using namespace std; void main () { string STRING; ifstream infile; infile.open ("names.txt"); while(!infile.eof) // To get you all the lines. { getline(infile,STRING); // Saves the line in STRING. cout<<STRING; // Prints our STRING. } infile.close(); system ("pause"); }

#include using namespace std; // function definition, to open file for reading... void openinfile(ifstream &infile) { char filename[100]; cout<<"Enter the file name: "; // Enter the filename that you have created // (can include path). From the comment above // you have to enter "C:\sampleread.txt" without the double quotes. cin>>filename; infile.open(filename); } void main(void) { // declare the input file stream ifstream inputfile; // declare the output file stream ofstream outputfile; char chs; // function call for opening file for reading... openinfile(inputfile); // create, if not exist and open it for writing outputfile.open("C:\\samplewrite.txt"); // test until the end of file while (!inputfile.eof()) { // read character until end of file inputfile.get(chs); if (!inputfile.eof()) { // output character by character (byte) on screen, standard output cout<<chs; // write to output file, samplewrite.txt outputfile<<chs; } cout<<"\nReading and writing file is completed!"<<endl; // close the input file stream inputfile.close(); // close the output file stream outputfile.close(); }

// using getline() member function #include using namespace std; void main(void) { char filename[50]; ifstream inputfile; char FirstLine[50]; char SecondLine[50]; char ThirdLine[50]; // prompt user for file name to be opened... cout<<"Enter the filename to be opened: "; cin>>filename; // test open file for reading... inputfile.open(filename); // if not the end of file, do... if(!inputfile.eof()) { cout<<"\nThe first line of text is: \n"; inputfile.getline(FirstLine, 50); cout<<FirstLine<<'\n'; cout<<"The second line of text is: \n"; inputfile.getline(SecondLine, 50); cout<<SecondLine<<endl; cout<<"The third line of text is: \n"; inputfile.getline(ThirdLine, 50); cout<<ThirdLine<<endl; } Output:

#include using namespace std; void main(void) { char filename[ ] = "C:\\testfileio.txt"; ifstream inputfile; inputfile.open(filename, ios::in); // test if fail to open fail for reading, do… if(inputfile.fail()) { cout<<"Opening "<<filename<<" file for reading\n"; cout<<" \n"; cout<<"The "<<filename<<" file could not be opened!\n"; cout<<"Possible errors:\n"; cout<<"1. The file does not exist.\n"; cout<<"2. The path was not found.\n"; system("pause"); exit(1); // just exit // 0-normal, non zero - some error } // if successful opening file for reading, do… else { cout<<"The "<<filename<<" file was opened successfully!\n"; cout<<"\nDo some file processing here...\n"; } inputfile.close(); // test if fail to close the file, do… if(inputfile.fail()) { cout<<"\nThe file "<<filename<<" could not be closed!\n"; system("pause"); exit(1); } // else, do… else cout<<"\nThe "<<filename<<" file was closed successfully!\n"; }

Reading data and do some calculation, then display the data. Firstly, create a file named testfileio1.txt on drive C:. Key in some data in this test file as shown below and save the file.

For example, here's how to open the file named "input.dat" for reading: #include ifstream inFile; inFile.open("input.dat"); if (inFile.fail()) { cerr << "unable to open file input.dat for reading" << endl; exit(1); }