Download presentation
Presentation is loading. Please wait.
Published byLeon Stevens Modified over 9 years ago
1
Writing to Files and Reading From Files
2
Writing Data to a File Creating a new file, a.dat or.txt file #include #include // for file writing #include //for Exit(1) #include using namespace std;
3
Opening File for Writing Data Note: 1.open(”fname ") is a function in fstream class. 2.Opening a file to write data will create the data file for you in the folder where you are currently working. If you want to see the data file you have to look for it in the same folder. You have been doing this all along and know where the file is being created. 3.Open your template and modify to look like the code below. int main () { //Declare variable outfile of ofstream data type (class) ofstream outfile ; outfile.open ("review.dat"); //Open file for writing outfile.close(); return 0; }
4
1.ofstream is a class within fstream. 1.It is a data type like int or double or string. 2.Remember we have #include fstream in our preprocessor directives. 3.outfile is a variable name and we could call it any other meaningful name like outstream or writefile. IMPORTANT : 1.If you open a data file that already exists, the data in that file will be erased. 2.Writing to this file will overwrite anything that is already there. 3.You need to be sure that you really want to do this.
5
Check That the File Exists and Can Be Opened 1.Always make sure the file exists and can be opened. 2.fail() like open() and close() are file manipulation functions available through fstream class. 3.The fail() function is used to determine if the file exists and it can be opened. 4.You will use the close() function when you are finished writing to or reading from a data file. 5.Note: the function exit(1) is in the cstdlib class requiring the #include cstdlib preprocessor directive. The exit(1) function stops program execution. 6.Add this to your code. If your template says: if writefile.fail() then change it to outfile.fail(). if (outfile.fail()) { cout << "\n\nFile cannot be opened.\n\n"; exit(1);//program halts }
6
Write Data to the File 1.The ofstream variable outfile is treated just like cout. The data is being written to a data file instead of to the monitor screen. 2.Below is a sample of a review quiz of some facts. You will eventually write your own review study guide for one of your final exams. 3.Add the following to your code and save it. 4.Desk check the code for errors. 5.Run the code and take a look at the data file. outfile << “What is the area of a rectangle with a length of 8ft and a width of 6ft?" << endl; outfile << "48"<< endl; outfile << “What is the perimeter of a rectangle with a length of 8ft and a width of 6ft?"<< endl; outfile << "28"<<endl; outfile << "What is the area of a right triangle of with a base of 8ft and a height of 6ft?"<< endl; outfile << "24"<<endl; outfile << "What is the perimeter of a right triangle of with a base of 8ft and a height of 6ft?"<< endl; outfile << "24"<<endl; outfile.close();//Data files that are opened must always be closed. return 0; }
7
The close() Function If the file is not closed when you are finished either writing to or reading from the file, your code will not work properly and all the data in the file could be lost. The file must be closed in the same function where it is opened. For top down design, call functions for all manipulations of data, such as counting correct answers or giving feedback to user about user input.
8
Read words from a file //Counts words read from a file #include #include // for file reading #include //for Exit(1) #include using namespace std; This is the same as the code for writing to a data file.
9
Opening file for reading Note the ifsrtream variable infile. 1.ifstream is a class within fstream. 1. It is a data type like int or double or string. 2.Remember we have #include fstream in our preprocessor directives. 3.infile is a variable name and we could call it any other meaningful name like instream or readfile. int main () { int counter=0;//counts words string word; ifstream infile; //Declaring variable name infile.open (”review.dat");//Open file for reading
10
Opening file for reading 1.Note the ifsrtream variable infile. See last slide for special note about this. 2.Before we write code to make a study guide for a final, we will simply count the words in the data file just to make sure we are reading the file properly. So we are declaring the counter and word variables. 3.You must know where the data file is and write the code to read the data file in the same folder that contains the data file. 4.Enter this code below: int main () { int counter=0;//counts words string word; ifstream infile; //Declaring variable name infile.open (”review.dat");//Open file for reading
11
Check for File Existence if (infile.fail()) { cout<<"File not found"; exit(1);//program halts }
12
Read Words in Data File Enter this code. Save file as countWords.cpp then run the program. while (infile>>word) // infile will read words until there is no word to be read { counter ++;// counts the words that are read. if(counter % 5 == 0) //What does this if block do? { cout<<endl; } cout << word << “ “; } cout<<endl<<endl; cout<<"The number of words in the file is: "<<counter<<"\n"; infile.close(); //Data files that are opened must always be closed. return 0; }
13
fstream member functions eof ( ) –TRUE if eof marker read on last operation open( ) –opens file for operations close( ) –closes file after use fail( ) –returns true if last operation on file failed.
14
eof() fragment #1:fragment #2: count = 0;count=0; while (!infile.eof () )while(infile>>num){ infile>>num;count++; count++;} }cout<<count<<endl; cout<<count<<endl; assume file contains:3 7 -2 4 result fragment 1:result fragment 2:
15
eof() fragment #1:fragment #2: count = 0;count=0; while (!infile.eof () )while(infile>>num){ infile>>num;count++; count++;} }cout<<count<<endl; cout<<count<<endl; assume file contains:3 7 -2 4 result fragment 1: 5result fragment 2: 4
16
Streams for reading files Everything we can do with cin, we can do the same with infile. Infile >>thing; –thing can be an int, a double, or a string. –Reading stops with a white space because of the –extraction operator >>. We can use getline() to read a whole line into a string. –string s –Getline(infile, s); //or while(getline(infile, s))
17
#include #include // for file reading #include //for Exit(1) #include using namespace std; int main () { string question, answer; ifstream infile; infile.open (“review.dat"); if (infile.fail()) { cout<<"File error"; exit(1);//program halts } while (getline(infile, question)) { getline(infile, answer); cout<<“the quesiton is:\n “<< question<< endl; cout<<“ The answer is: \n “<< answer<<“\n\n”; } infile.close(); return 0; } Save previous file as readQ_A.cpp. Replace the body with codebelow: Save again and run the program that outputs the questions and the answers.
18
Test Program For Your Exam Data The program readQ_A.cpp should be run with your study guide for the final. This is a test that your data is stored properly, can be read properly, and then output all the questions and answers correctly. This is how you can be sure that there is nothing wrong with your data file.
19
#include #include // for file reading #include //for Exit(1) #include using namespace std; int main () { string question, answer; ifstream infile; infile.open ("review.dat"); if (infile.fail()) { cout<<"inFile error"; exit(1);//program halts } ofstream outfile; outfile.open ("output.dat”, ios::app ); if (outfile.fail()) { cout<<" outFile error"; exit(1);//program halts } while (getline(infile, question)) { getline(infile, answer); cout<<"the quesiton is:\n "<< question<< endl; outfile<<"the quesiton is:\n "<< question<< endl; cout<<" The answer is: \n "<< answer<<"\n\n"; outfile<<” The answer is: \n “<< answer<<"\n\n"; } infile.close(); outfile.close(); return 0; } Check this out. Writing output to a file.
20
1.Make these changes below to your code. 2.Savecode as feedback,cpp and run the program. 3.This will output correct or incorrect for your answer to the question instead of printing out the answer. 4.Under getline(infile, answer); Type: correct = answer; 4.Change these lines: –cout << “\n\nThe answer is: \n” cout << answer<<"\n\n";} To the following code: getline(cin, response); if (response != correct ) { cout << “This is not the correct answer.” ; } else { cout<< “ Correct answer. Good Job!!”; } 5. Save and run the program. int main () { string question, answer, correct, response; ifstream infile; infile.open("Desktop/C++Programs/review.dat"); if (infile.fail()) { cout<<"\n\nFile cannot be opened.\n\n"; } while (getline(infile, question)) { getline(infile, answer); cout << "The quesiton is: \n”; cout << question; } infile.close(); return 0; }
21
Study Guide Assignment You are going to create several files. 1.A data (.dat) file like review.dat that consist of questions and answers that you can use as a study guide for one of your final exams. The answers should be a single word, character, or number read as a string. –Discuss why the answers should be single word, character, or number. On the first line, write the first question. Press return. On the second line, write the correct answer to the question and press return. Continue this way until you have entered up to 21 questions and correct answers. This file may have fewer problems if you create it like the writefile program we did in the model. You are likely to have the least number of problems if you make the review questions multiple choice. Continued on next slide----------------------------------------------->
22
Study Guide Assignment 2. Create a.cpp file like feedback.cpp that reads the questions and correct answers. This may require a series of getlines to read the whole question and a series of getlines to read the answer choices, Or See page 457 in Chapter 8. Discuss using a terminating character in getline(cin, question, '.') statement. It is in this file that you get to be really creative and put your own stamp on this project. You should feel proud to put your name to it and have a rewarding sense of personal accomplishment when it is completed. See more about this file in the next slide. 3. Create an output.dat file. This is created in a function of the above.cpp that writes to the output.dat file everything that shows up on the screen as out put when the program is run. 4.Create a score.dat file. This is created in a different function of the above.cpp file recording final score and comments. Continued on next slide----------------------------------------------->
23
Study Guide Assignment In your.cpp file that reads the questions and correct answers: –Have counter for how many right responses in order to calculate give a grade at the end of the review. –The calculation should be in a different function. –For wrong answers, give two more chances to get it right. This also should be in a different function. –You can decide how to handle it if the answer is wrong three times. Give the right answer. Give clues. Give encouragement about studying and taking this review over again. These are only examples of how you might handle it. VERY IMPORTANT: –You must use top down design. Have only function calls in the int main(), and some function calls within the functions if needed. Continued on next slide.----------------------------------------->
24
Study Guide Assignment Requirements –It is most important that the review meaningful to you. –**Your review has to be uniquely yours. ** –If you are preparing a review for the same course as someone else, your questions and answers must be different. –It is ok to help each other study by running one another’s review. –It is ok to share with others if you learn something helpful. –It is ok to help each other out with problems, but I do not want to see identical or very similar code throughout the program. –Your first big job is data collection: Decide which course you want for the study guide. Collect likely questions for the study guide that require single word, character, or number answers; all read as strings, or multiple choice. If using multiple choice, The wrong choices should be likely choices for someone that did not really know the material. Continued………………………………………………>
25
Final Exam Have this program ready for me to check before the final exam. It would be a very good idea to have it done well before the final and to already have credit for it before coming to the final. The next slide has a loose outline of an example of possible top-down design. ID and specs, #includes, and prototypes are needed but not shown here. Continued………………………………………………>
26
Sample outline of top down design for your exam: int main() { double count=0; instructions(); get_questionsAnswers(count); results(count); return 0; } void instructions() //post tell user how to use the guide { ~~~~~~~~~~~ } void get_questionsAnswers(double &count); { string question, correct ; ifstream infile; infile.open(‘- - - `.dat’) /*Do if ( infile.fail()) routine. Then loop to readi eachquestions and correct answer, Call feedback funceion.within the loop at the end of the loop * feedback(question, correct, count); infile.close(); } void feedback(string question, string correct, double &count) { ofstream outfile; outfile.open (“output.dat”, ios::app); // ios::app allows file to be opened, keep data already there, // and append new data to file. /*After if( outfile.faill() routine, cout<< and outfile the question. Ask for user response and outfile<< the user response, cout<<and outfile<< the feed back to user about users answer. You be creative here,and may need to call another function*/ outfile.close(); } void results(double count) { ofstream outfile; outfile.open (“score.dat”); /* Do outfile.fail()routine. Calculate final score. Both c cout<<, and outfile<< score and comments about the score. You be creatiive here and may need to call other functions. */ outfile.close() }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.