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

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

Embed Size (px)

Citation preview

File input and output in C++

Dr. Ahmed Telba

CSE202: Lecture 9 The Ohio State University 2

Reading & Writing to Files

CSE202: Lecture 9 The Ohio State University 3

helloworld.cpp#include <iostream>using namespace std;

int main(){ cout << "Hello World!" << endl; cout << "Goodbye World!" << endl;

return 0; }

CSE202: Lecture 9 The Ohio State University 4

helloworld.cpp#include <iostream>using namespace std;

int main(){ cout << "Hello World!" << endl; cout << "Goodbye World!" << endl;

return 0; }

> helloworld.outputHello World!Goodbye World!

>

CSE202: Lecture 9 The Ohio State University 5

Writing to Files

CSE202: Lecture 9 The Ohio State University 6

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 <fstream>

CSE202: Lecture 9 The Ohio State University 7

Writing to Files: Output File Stream

• To write a file:

1. Create an output stream object2. Establish connection to a file3. Check Validity4. Start writing5. Close the file

CSE202: Lecture 9 The Ohio State University 8

writeFile1.cpp#include <cstdlib> // function exit() is in cstdlib#include <fstream> // class ofstream() is in fstream#include <iostream>

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 9 The Ohio State University 9

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 9 The Ohio State University 10

Writing to Files (1)

1. “Create an output stream object”– Make sure we included the <fstream> 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 9 The Ohio State University 11

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 9 The Ohio State University 12

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 9 The Ohio State University 13

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 <cstdlib>

CSE202: Lecture 9 The Ohio State University 14

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 9 The Ohio State University 15

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 9 The Ohio State University 16

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 9 The Ohio State University 17

writeFile2.cpp#include <cstdlib> // function exit() is in cstdlib#include <fstream> // class ofstream() is in fstream#include <iomanip>#include <iostream>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 9 The Ohio State University 18

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 9 The Ohio State University 19

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 9 The Ohio State University 20

writeMultiFile.cpp (cont) cout << "Writing to files book1.txt and book2.txt." << endl;

// write to book1.txt fout1 << "Assets: $" << 10000 << endl; fout1 << "Liabilities: $" << 15000 << endl;

// write to book2.txt fout2 << "Assets: $" << 12000 << endl; fout2 << "Liabilities: $" << 9000 << endl;

fout1.close(); // close file stream fout1 fout2.close(); // close file stream fout2

return 0; }

CSE202: Lecture 9 The Ohio State University 21

Asking for the File Name• Read the input file name into a string:

#include <string>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 9 The Ohio State University 22

writeFile3.cpp. . .#include <fstream> #include <string> // 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 9 The Ohio State University 23

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 9 The Ohio State University 24

Reading from Files

CSE202: Lecture 9 The Ohio State University 25

Reading from Files: Input File Stream

• To read from a file:

1. We need a-priori knowledge of the file format2. Create an input stream object3. Establish connection to a file4. Check Validity5. Start reading6. Close the file

CSE202: Lecture 9 The Ohio State University 26

readFile1.cpp#include <cstdlib> // function exit() is in cstdlib#include <fstream> // class ofstream() is in fstream#include <iostream>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 9 The Ohio State University 27

readFile1.cpp (cont)

// read text from file fin >> x; cout << "Read integer: " << x << endl; // close file stream fin fin.close();

return 0; }

CSE202: Lecture 9 The Ohio State University 28

> readFile1.exeRead integer: 77

>

… // read text from file fin >> x; cout << "Read integer: " << x << endl;

File: intList1.txt

77

65 28

33

112

CSE202: Lecture 9 The Ohio State University 29

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 3.89 334 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 9 The Ohio State University 30

Reading from Files (2)

2. “Create an input stream object”– Again, make sure we included the <fstream>

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 9 The Ohio State University 31

Reading from Files (3)

3. “Establish a connection to a file”

– Open the file “intList1.txt”:

fin.open(“intList1.txt”, ios::in);

CSE202: Lecture 9 The Ohio State University 32

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 9 The Ohio State University 33

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 9 The Ohio State University 34

Reading from Files (6)

6. “Close the file”– Like before, we close the file after we are done

using it:

fin.close();

CSE202: Lecture 9 The Ohio State University 35

readFile2.cpp. . .#include <fstream>#include <string>. . .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 9 The Ohio State University 36

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 9 The Ohio State University 37

> readFile2.exeEnter file name: intList1.txtRead integer: 77Read integer: 65Read integer: 28Read integer: 33Read integer: 112

>

… // read text from file for (int i = 1; i <= 5; i++) { fin >> x; cout << "Read integer: " << x << endl; }…

File: intList1.txt

77

65 28

33

112

CSE202: Lecture 9 The Ohio State University 38

> readFile2.exeEnter file name: missing.txtUnable 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 9 The Ohio State University 39

> readFile2.exeEnter file name: intList2.txtRead integer: 10Read integer: 20Read integer: 20Read integer: 20Read integer: 20

>

… // read text from file for (int i = 1; i <= 5; i++) { fin >> x; cout << "Read integer: " << x << endl; }…

File: intList3.txt1020

CSE202: Lecture 9 The Ohio State University 40

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 9 The Ohio State University 41

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 9 The Ohio State University 42

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 9 The Ohio State University 43

fail()

• To read all integers in a file:

fin >> x; while (!fin.fail()) { // Process x...

fin >> x; }

CSE202: Lecture 9 The Ohio State University 44

> readFile3.exeEnter file name: intList1.txtRead integer: 77Read integer: 65Read integer: 28Read integer: 33Read integer: 112

>

… // read text from file fin >> x; while (!fin.fail()) { cout << "Read integer: " << x << endl; fin >> x; }…

File: intList1.txt

77

65 28

33

112

CSE202: Lecture 9 The Ohio State University 45

> readFile3.exeEnter file name: intList2.txtRead integer: 10Read integer: 20Read integer: 30Read integer: 40Read integer: 50Read integer: 60Read integer: 70

>

… // read text from file fin >> x; while (!fin.fail()) { cout << "Read integer: " << x << endl; fin >> x; }…

File: intList1.txt10203040506070

CSE202: Lecture 9 The Ohio State University 46

> readFile3.exeEnter file name: intList3.txtRead integer: 10Read 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 9 The Ohio State University 47

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 9 The Ohio State University 48

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 9 The Ohio State University 49

fail()

ifstream fin;

• The condition: while(fin)is equivalent to: while(!fin.fail())

CSE202: Lecture 9 The Ohio State University 50

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 9 The Ohio State University 51

… // read text from file fin >> x; while (!fin.fail()) { cout << "Read integer: " << x << endl; fin >> x; }…

File: intListBad.txt

77

65 28

Hello

33

112

• What happens when readfFile3.exe is run on file intListBad.txt?

CSE202: Lecture 9 The Ohio State University 52

eof(): End of File

• The eof() function is true when the function reaches the end of file.

CSE202: Lecture 9 The Ohio State University 53

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 9 The Ohio State University 54

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 9 The Ohio State University 55

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 9 The Ohio State University 56

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 9 The Ohio State University 57

> readFile5.exeEnter file name: intListBad.txtRead integer: 77Read integer: 65Read integer: 28Error reading file intListBad.txt

>

… if (!fin.eof()) // check for error { cerr << "Error reading file " << file_name << endl; exit(20); }…

File: intListBad.txt

77

65 28

Hello

33

112

CSE202: Lecture 9 The Ohio State University 58

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 <iostream>#include <fstream>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 <iostream>#include <fstream>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 <iostream>#include <fstream>#include <string>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 <iostream> #include <fstream>#include <stdlib.h>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

• 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 <iostream>• #include <fstream> • 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 >>) 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 <iostream>• #include <fstream>• 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 <iostream>#include <fstream>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• // output file#include<iostream>#include<fstream>

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 <iostream> #include <fstream> # include <string> 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 <iostream>• #include <fstream>• 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 <iostream>• #include <fstream>• 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 <iostream>• #include <fstream>• 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 <fstream>• ifstream inFile;• inFile.open("input.dat"); • if (inFile.fail())• { cerr << "unable to open file input.dat for reading" << endl; exit(1); }