Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

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

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

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

4 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! >

5 CSE202: Lecture 9The Ohio State University5 Writing to Files

6 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

7 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

8 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); }

9 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; }

10 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”

11 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);

12 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); }

13 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

14 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

15 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.

16 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).

17 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); }

18 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; }

19 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); }

20 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: $" << 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; }

21 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);

22 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); }

23 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; }

24 CSE202: Lecture 9The Ohio State University24 Reading from Files

25 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

26 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); }...

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

28 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 77 65 28 33 112

29 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 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.

30 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”

31 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);

32 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); }

33 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;

34 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();

35 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); }

36 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; }

37 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 77 65 28 33 112

38 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); } …

39 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

40 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); }

41 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; }

42 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.

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

44 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 77 65 28 33 112

45 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 10 20 30 40 50 60 70

46 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

47 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); }

48 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; }

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

50 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.

51 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 77 65 28 Hello 33 112 What happens when readfFile3.exe is run on file intListBad.txt ?

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

53 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); }

54 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; }

55 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); }

56 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.

57 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 77 65 28 Hello 33 112

58 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.

59

60 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);

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

62 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; }

63 // 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; }

64 // 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; }

65 // 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; }

66 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.

67 // 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; }

68 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.

69 / 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; }

70 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; }

71 // 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; }

72 #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"); }

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

74 // 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:

75 #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"; }

76 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.

77 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); }

78

79

80


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

Similar presentations


Ads by Google