File I-O
Computer Science 10b with Wittman at University of California - Los Angeles
About this note
By: Anonymous
Textbook:
Big C++ with WeL Total Java CD Metrowerks Codewarrior 8 and Sleve for Horstmann Big C++ Set
Created: 2009-01-22
File Size: 9 page(s)
Views: 7
Textbook:
Big C++ with WeL Total Java CD Metrowerks Codewarrior 8 and Sleve for Horstmann Big C++ SetCreated: 2009-01-22
File Size: 9 page(s)
Views: 7
About StudyBlue
STUDYBLUE makes things that make you better at school.
Things like online flashcards with photos and audio.
Things like personalized quizzes and friendly reminders about when (and what) to study next.
Think of it as a digital backpack™: access to all of your study materials online and on your phone.
STUDYBLUE exists to make studying efficient and effective for every student, for free. Join us.
“I have used this website for three exams, and I see a huge difference in my test results.”
Naj
Naj
Sign up (free) to study this.
1 Lecture 24: File I/O PIC 10A Todd Wittman Sec 12.1: File Streams square6 Recall cin/cout are the I/O streams for the console window. square6 We can create our own I/O streams to read/write data different places. square6 In particular, we can create streams to read from and write to text files using the library. square6 Declaring a stream is a lot like creating a variable. I like to call my file I/O streams fin & fout. (Other names work too!) ifstream fin; // A file input stream. ofstream fout; // A file output stream. square6 We can then use this stream to open a file and perform reading and writing procedures just like cin/cout. int x; fin >> x; //Read x from the file associated with fin. fout << x; //Write x to fout?s file, could be a different file. 2 A Basic Example square6 Write hello to the text file ?out.txt?. #include //Need the file I/O library. using namespace std; int main() { ofstream fout; //Create an output stream. fout.open(?out.txt"); //Open the file out.txt for writing. fout << "Hello Middle Earth!"; fout.close(); //Close the file when we?re done. return 0; } Opening Files square6 Suppose we want to read a list of integers in the text file ?list.txt?. square6 The numbers could be separated by spaces or line breaks. square6 First we need to create the input stream and open the file for reading with this stream. ifstream fin; fin.open(?list.txt?); square6 This associates the file ?list.txt? with fin. 42 15 -32 12 88 96 -12 2 33 44 -88 -22 37 2 1 0 1 2 3 list.txt 3 Opening Files square6 We could also have opened a file name given by the user. string file_name; cin >> file_name; ifstream fin; fin.open( file_name.c_str( ) ); square6 We add c_str( ) to convert the string to a char array. square6 We need this because open( ) is an older function that doesn?t recognize strings. Reading Files square6 To read the first #: int x; fin >> x; // Now x=42. square6 We can read the whole file with a loop and place the numbers in an array or vector. square6 If we don?t know how many numbers there are ahead of time, probably best to use a vector. square6 Recall (cin>>x) is actually a boolean. Returns false if there was no integer x to read. Our ifstream fin works likewise. vector list; // Creates empty int vector. int x; while (fin >> x) list.push_back(x); // Adds x to the end. square6 When you?re done reading, remember to close the file. fin.close( ); 4 Putting It All Together #include #include #include #include using namespace std; string file_name; cout << ?Enter file name to read: ?; cin >> file_name; ifstream fin; fin.open(file_name.c_str( )); vector list; int x; while (fin >> x) list.push_back(x); fin.close( ); int total=0; for (int i=0; i < list.size(); i++) total += list[i]; double average = (double) total / list.size(); cout << ?The average is ? << average << ?\n?; square6Ex Read the integers in a file given by the user and then output the average to the console. ?Did we really need to use a vector in this example? Reading File to Parallel Vectors square6 Recall we talked about storing products? name, price, and score in 3 parallel vectors. square6 Let?s read the data in the file ?games.txt? to 3 parallel vectors name, price, and score. square6 Then we?ll output each product?s bang-for-the-buck ratio. Wii PC Mac PS3 XBox360 249.99 1299 800 600 499.49 8 5 6 3 7 Atari2600 2.99 10 Name Price Score 0 1 2 3 4 5 Wii 249.99 8 PC 1299 5 Mac 800 6 PS3 600 3 XBox360 499.49 7 Atari2600 2.99 10 games.txt 5 Reading File to Parallel Vectors ifstream fin; fin.open(?games.txt?); vector name; vector price; vector score; string s; double d; int i; while (fin >> s >> d >> i) { name.push_back(s); price.push_back(d); score.push_back(i); } fin.close( ); for (int j = 0; j < name.size( ); j++) cout << name[j] << ?\?s ratio is ? << price[j] / score[j] << ?\n?; Stops reading when it doesn?t find a string-double-int combo to read or runs into the end of the file. Wii PC Mac PS3 XBox360 249.99 1299 800 600 499.49 8 5 6 3 7 Atari2600 2.99 10 Name Price Score 0 1 2 3 4 5 Writing to a File square6 Writing to a file is very similar, except we create an output stream and the arrows << go the other way. square6 Let?s write out the first 100 integers to the file ?first100.txt?. ofstream fout; fout.open(?first100.txt?); for (int i = 1; i <= 100; i++) fout << i << ?\n?; fout.close( ); square6 If the file ?first100.txt? did not exist, it will be created. square6 If the file did exist, we will overwrite what was there previously. All existing data will be lost. square6 If you want to append the data rather than overwrite, use fout.open (?first100.txt?, ios::app); 6 Formatting Output square6 Recall that we can line up our output in columns using the setw function in . What does the code below do? #include #include using namespace std; int main ( ) { ofstream fout; fout.open(?first100.txt?); for (int i = 1; i <= 100; i++) { fout << setw(5) << i; if (i%10 == 0) fout << ?\n?; } fout.close( ); return 0; } We can also control # decimal places on doubles with setprecision(int). Example: Pig Latin square6 In Pig Latin, if the first letter of a word is a consonant it is moved to the end and the suffix ?-ay? is added. computer programming omputercay rogrammingpay square6 If the first letter is a vowel (aeiou), we just add ?-ay? to the end. arthur also under arthuray alsoay underay square6 Let?s write a program that reads a text file given by the user and converts it to Pig Latin. The output is written to a file also supplied by the user. square6 For this example, suppose the file contains all words, all lower-case, no punctuation. The output is all one line. square6 (We'll handle the harder cases later.) square6 oday eway eallyray eednay otay useay ectorsvay? 7 Example: Pig Latin square6 The following function takes a string and returns the Pig Latin equivalent of that word. translate2PigLatin ("hello") returns "ellohay" translate2PigLatin ("awesome") returns "aweseomeay" string translate2PigLatin (string word) { if (word[0]==?a? || word[0]==?e? || word[0]==?i? || word[0]==?o? || word[0]==?u?) return word + ?ay?; else return word.substr(1,word.length()-1) + word[0] + ?ay?; } string in_file, out_file; cout << ?Enter the file to read: ?; cin >> in_file; cout << ?Enter the destination file: ?; cin >> out_file; ifstream fin; fin.open(in_file.c_str( )); ofstream fout; fout.open(out_file.c_str( )); string word; while (fin >> word) { word = translate2PigLatin(word); fout << word << ? ?; } fin.close( ); fout.close( ); Example: Pig Latin 8 The get Function square6 We could also read the file one char at a time using ifstream member function get(char). char c; fin.get(c); square6 This places the character in fin?s current position into the char variable c. square6 If you don?t like what you saw, you could back up one character with fin.unget( ); square6 This is useful for detecting line breaks: if (c==?\n?) square6 Suppose we want our Pig Latin translator to output line breaks in the same place as the input file. computer programming is fun omputercay rogrammingpay isay unfay Detecting Line Breaks square6 To put line breaks in the corresponding position, we just add a few lines to our Pig Latin example. (Assumes line break occurs immediately after the word.) string word; char c; while (fin >> word) { word = translate2PigLatin(word); fout << word << ? ?; fin.get(c); if (c==?\n?) fout << ?\n?; } 9 Detecting Capitals and Punctuation square6 What if we want to do the harder case with punctuation and capital letters? "Hello!" "Ellohay!" square6 First we want to detect punctuation and capital letters. square6 The two functions below might help us. (#include ) bool checkPunctuation (string word) { bool checkCapital (string word) { char c = word[word.size()-1]; char c = word[0]; if (c=='.' || c==',' || c==';' || c==':' || c=='!' || c=='?') return isupper(c); return true; } else return false; } square6 What assumptions do we make on the word here? string word; char c; while (fin >> word) { bool hasPunctuation = checkPunctuation(word); char mark; if (hasPunctuation) { mark = word[word.length()-1]; word = word.substr(0,word.length()-1); } bool hasCaps = checkCapital(word); if (hasCaps) word[0] = tolower(word[0]); word = translate2PigLatin (word); if (hasCaps) word[0] = toupper(word[0]); if (hasPunctuation) word.push_back(mark); fout << word << ? ?; fin.get(c); if (c==?\n?) fout << ?\n?; } Check for punctuation at end. Remove punctuation mark (temporarily) if there is one. Check for capital letter at front. Change to lower-case (temporarily). Translate the word. If it had capital originally, capitalize first letter. If it originally had punctuation, add mark to end. Note strings are vectors!!! Check for line break as before. localadmin Microsoft PowerPoint - Lec24.ppt
Back
Next
About this note
By: Anonymous
Textbook:
Big C++ with WeL Total Java CD Metrowerks Codewarrior 8 and Sleve for Horstmann Big C++ Set
Created: 2009-01-22
File Size: 9 page(s)
Views: 7
Textbook:
Big C++ with WeL Total Java CD Metrowerks Codewarrior 8 and Sleve for Horstmann Big C++ SetCreated: 2009-01-22
File Size: 9 page(s)
Views: 7
About StudyBlue
STUDYBLUE makes things that make you better at school.
Things like online flashcards with photos and audio.
Things like personalized quizzes and friendly reminders about when (and what) to study next.
Think of it as a digital backpack™: access to all of your study materials online and on your phone.
STUDYBLUE exists to make studying efficient and effective for every student, for free. Join us.
“I have used this website for three exams, and I see a huge difference in my test results.”
Naj
Naj