1 / 34

Today’s Lecture

This lecture covers the concepts of input/output (I/O) streams, including console I/O and file I/O, in C++. It explains how streams are used to deliver program input and output and provides examples of their usage. The lecture also discusses sequential and random access to files and demonstrates file connection and file I/O libraries.

tadame
Download Presentation

Today’s Lecture

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Today’s Lecture • I/O Streams • Console I/O • File I/O • Tools for File I/O • Sequential Access & Random Access to Files

  2. Introduction • Streams • Special objects • Deliver program input and output • In C++ • Console I/O is working with streams • File I/O is also working with streams

  3. Streams • Stream: A flow of data • Input stream • Flow into program • Can come from keyboard • Can come from file • Output stream • Flow out of program • Can go to screen • Can go to file

  4. Streams Usage • We’ve used streams already • cin • Input stream object connected to keyboard • cout • Output stream object connected to screen

  5. Stream Example int num1, num2, total; cout << "First number: "; cin >> num1; cout << "Second number: "; cin >> num2; total = num1 + num2; cout << “total = " << total << endl;

  6. Streams Usage • We’ve used streams already • cin • Input stream object connected to keyboard • cout • Output stream object connected to screen • Can define other streams • To or from files • Used similarly as cin, cout

  7. Streams Usage Examples: cin, cout • Consider: • Using the pre-defined stream cinint Number;cin >> Number; • Reads value from stream (keyboard), assigned to Number • Using the pre-defined stream coutcout << Number; • Writes value to stream (monitor)

  8. Streams Usage Like cin, cout • Consider: • Given program defines stream inStreamthat comes from some file:int Number;inStream >> Number; • Reads value from stream (file), assigned to theNumber • Program defines stream outStream that goesto some fileoutStream << theNumber; • Writes value to stream, which goes to file

  9. Files • Reading from file • When program takes input • Writing to file • When program sends output • Start at beginning of file (Sequential access) • Other methods available

  10. File Connection • Must first create a file stream object • Then connect the file to the file stream object • For input only: • File ifstream object • For output only: • File ofstream object • Classes ifstream and ofstream • Defined in library <fstream> • Named in std namespace

  11. File I/O Libraries • To allow both file input and output in your program:#include <fstream>using namespace std;

  12. Declaring Streams Objects (Variables) • Stream must be declared like any otherclass variable:ifstreaminput_file_stream;ofstreamout_file_stream; • Must then "connect" to file:input_file_stream.open("infile.txt"); • Called "opening the file" • Uses member function open • Can specify complete pathname

  13. Streams Usage • Once declared and connected, use it like cin and cout! int N; input_file_stream >> N; • Output stream similar:ofstreamoutput_file_stream;output_file_stream.open("outfile.txt");output_file_stream << "Number = " << N;

  14. Closing Files • Files should be closed • When program completed getting input orsending output • Disconnects stream from file • In action:input_file_stream.close();output_file_stream.close();

  15. File Example: Display 12.1 Simple File Input/Output (1 of 2)

  16. File Example: Display 12.1 Simple File Input/Output (1 of 2)

  17. Appending to a File • Standard of stream open operation begins with empty file • Even if file exists  contents lost • Open for append:ofstreamoutStream;outStream.open("important.txt", ios::app); • If file doesn’t exist  creates it • If file exists  appends to end

  18. Compare Console I/O and File I/O • All cin functions are same for files! • Read in (send out) integers (int) • Read in (send out) characters (char) • Read in (send out) floating-point s (float) • …. • For String operating: • >> read one word (separated by spaces, new lines) • getline() read one line of words

  19. Compare Console I/O and File I/O (continued) • For console String (C-string) operations • char S[100]; cin >> S; • read one word • char S[100]; cin.getline(S, 20) ; • read one line of words

  20. Compare Console I/O and File I/O (continued) • For file String (C-string) operations ifstreamifm;ifm.open("infile.txt"); • char S[100]; ifm >> S; • read one word • char S[100]; ifm.getline(S, 20) ; • read one line of words

  21. Compare Console I/O and File I/O (continued) • cout is same for file operations (say fout) ofstreamfout; fout.open(“output.txt", ios::app); cout << “whatever\n” fout << “whatever\n” • Whatever displayed on screen will be same as those saved in file

  22. More I/O member functions • See Appendix 4 of the textbook Stream_var.open(“File name”); Stream_var.close(); Strean_var.eof(); Stream_var.get(char_var); Stream_var.getline(cstring_var, length);

  23. Checking End of File • Use loop to process file until end • An extraction operator actually returns a boolean value inStrem >> next Return true if the read was successful (space and new line will not be read) and returns false when code attempts to read beyond the end of the file Int next, sum =0; while (inStream >> next) { sum = sum + next; } cout << “ the sum is “ << sum << endl;

  24. Checking End of File • Use loop to process file until end inStrem.get(next) Return true if the read was successful and returns false when code attempts to read beyond the end of the file char next, sum =0; while (inStream.get(next)) { sum = sum + 1; } cout << “ the total number of characters is “ << sum << endl;

  25. Checking End of File • Use loop to process file until end inStrem.getline(next, length) Return true if the read was successful and returns false when code attempts to read beyond the end of the file Char[] next, sum =0; while (inStream.getline(next, 100)) { sum = sum + 1; } cout << “ the total number of lines is “ << sum << endl;

  26. Which Function to Write • The easiest one and works for any text data • <<

  27. Which Function to Read • Numbers (Integer / floating-point) file: numbers are separated by blank space(s) • >> • Text file: words are separated by blank space(s): each word is going to be processed separately • >>

  28. Which Function to Read (continued) • Character files • each character (including space) needs to be processed individually • get(char s) • Ignore spaces, new lines, and tab • >> • Character files: one line is a record • getline(char s[], int size)

  29. Tools: File Names as Input • Stream open operation • Argument to open() is string type • Can be literal (used so far) or variablechar fileName[16];ifstream inStream;cout << "Enter file name: ";cin >> fileName;inStream.open(fileName); • Provides more flexibility

  30. File Access Applications Copy files • Copy char by char • Copy line by line Process files: • Determine how many specific characters • Count words • Count lines • Work on numbers

  31. Read and Write can be Performed at the Same Time • Opens same as istream or ostream • Adds second argument • fstreamrwStream;rwStream.open("stuff", ios::in | ios:: out); • Opens with read and write capability • It is confusing where to read and where to write: not recommend to use.

  32. Random Access to Files • Sequential Access • Most commonly used • So far we have talked about • Random Access • Rapid access to records • Access "randomly" to any part of file

  33. Random Access Tools • Move about in file • rwStream.seekp(1000); • Positions put-pointer at 1000th byte • rwStream.seekg(1000); • Positions get-pointer at 1000th byte • Not a requirement for this course

  34. Summary of File Operations Read from a file Write to a new or existing file Delete a file Copy a file Move a file Modify a file

More Related