Presentation is loading. Please wait.

Presentation is loading. Please wait.

Student Book Input / Output in C++

Similar presentations


Presentation on theme: "Student Book Input / Output in C++"— Presentation transcript:

1 Student Book Input / Output in C++
Unit - 10 IOStream Library Input / Output in C++

2 Student Book Unit Introduction This unit covers different features in standard IOStream Library

3 Unit Objectives After covering this unit you will understand…
Student Book Unit Objectives After covering this unit you will understand… IOStream library File operations Buffering operations Seeking operations Output stream formatting IOStream manipulators Creating manipulators

4 IOStream Introduction
Student Book IOStream Introduction Input and Output are the basic programming functions Without IOStream Library: requires hundreds of lines of code for usage and manipulation are error prone with dangling pointers, uninitialized pointers etc

5 IOStream Library IOStream Library helps in:
Student Book IOStream Library IOStream Library helps in: ease of coding error handling safer and efficient results Deals with the following I/O functions in a safe, efficient and easier manner: Standard Input Standard Output Files Memory Blocks Iostream Library comes with the standard C++ libraries for I/O functions and manipulations

6 IOStreams Features Provides an easier interface
Student Book IOStreams Features Provides an easier interface Handles menial tasks like closing the file pointer, when the file is not in use etc Error handling is automatic when I/O error occurs Constructor handles all the initialisation Destructor handles all the cleanup tasks like removing dangling pointers, memory cleanup etc

7 File IOStreams File IOStreams are simple to use: Declare an Object
Student Book File IOStreams File IOStreams are simple to use: Declare an Object Use the file I/O functions Destroy the object (the destructor is called automatically when the object goes out of scope)

8 Example: File IOStreams
Student Book Example: File IOStreams #include <fstream.h> #include <iostream.h> void main() { const int sz = 100; // Buffer size; char buf[sz]; ifstream in(”myfile.cpp"); // Read ofstream out(”myfile.out"); // Write int i = 1; // Line counter while(in.get(buf, sz)) { // Line input in.get(); // get() does not read ‘\n’ cout << buf << endl; // use endl for ‘\n’ // File output just like standard I/O: out << i++ << ": " << buf << endl; This simple program demonstrates the ease of use in IOstream. This program reads from a file and writes the data to another. The ‘get’ method of IOStream does not read the newline character and therefore it must be thrown away and must have an implicit ‘\n’ after each line read.

9 Example: File IOStreams (contd.)
Student Book Example: File IOStreams (contd.) } } // Destructors close in & out ifstream in(”myfile.out"); // More convenient line input: while(in.getline(buf, sz)) { char* cp = buf; while(*cp != ':') cp++; cp += 2; // Past ": " cout << cp << endl;

10 Student Book File Open Modes You can control the way a file is opened by changing a default argument These flags can be combined using a bitwise OR The different modes are: ios::in ios::out ios::app ios::nocreate ios::in Opens an input file. Use this as an open mode for an ofstream to prevent truncating an existing file ios::out Opens an output file. When used for an ofstream without ios::app, ios::ate or ios::in, ios::trunc is implied ios::app Opens an output file for appending. ios::ate Opens an existing file (either input or output) and seeks the end. ios::nocreate Opens a file only if it already exists. (Otherwise it fails.) ios::noreplace Opens a file only if it does not exist. (Otherwise it fails.) ios::trunc Opens a file and deletes the old file, if it already exists. ios::binary Opens a file in binary mode. Default is text mode.

11 File Open Modes (contd.)
Student Book File Open Modes (contd.) ios::noreplace ios::trunc ios::binary

12 Buffering in IOStreams
Student Book Buffering in IOStreams You can buffer all the bytes in a file using buffering It provides an easy and efficient solution to reading files or other I/O features Can be useful for manipulating file data. Read the file data, apply manipulation and write back Can also be useful for files that require frequent read/write operations

13 Example: Buffering IOStreams
Student Book Example: Buffering IOStreams #include <fstream.h> #include <iostream.h> void main() { ifstream in(“myfile.cpp”); cout << in.rdbuf(); // outputs entire file // another way to output the file while (in.get(*cout.rdbuf())) // redirects it to cout in.ignore(); // ignore the terminator ‘\n’ } This simple program reads all the data in a buffer and then displays the buffer content.

14 Student Book Seeking in IOStream You can move the stream pointer to different positions and read or write bytes There are three seek functions: ios::beg From beginning of stream ios::cur Current position in stream ios::end From end of stream

15 Example: Seeking in IOStream
Student Book Example: Seeking in IOStream #include <iostream> #include <fstream> void main() { ifstream in("Iofile.cpp"); ofstream out("Iofile.out"); out << in.rdbuf(); // Copy file in.close(); out.close(); // Open for reading and writing: ifstream in2("Iofile.out", ios::in | ios::out); ostream out2(in2.rdbuf()); cout << in2.rdbuf(); // Print whole file out2 << "Where does this end up?"; out2.seekp(0, ios::beg); // put pointer This example shows the file seek functionality. When the second file is opened in read/write mode, anything put in the file is appended at the end. It then seeks the start of the file and puts the like “and what about this?”

16 Example: Seeking in IOStream (contd.)
Student Book Example: Seeking in IOStream (contd.) out2 << "And what about this?"; in2.seekg(0, ios::beg); // get pointer cout << in2.rdbuf(); }

17 Output Stream Formatting
Student Book Output Stream Formatting You can format the output stream in STL, just like you can using printf in C++ The different formatting functions are: Internal formatting data ios::skipws ios::showbase ios::showpoint ios::uppercase ios::showpos ios::unitbuf Internal formatting data ios::skipws Skip white space. (For input; this is the default.) ios::showbase Indicate the numeric base (dec, oct, or hex) when printing an integral value. The format used can be read by the C++ compiler. ios::showpoint Show decimal point and trailing zeros for floating-point values. ios::uppercase Display uppercase A-F for hexadecimal values and E for scientific values. ios::showpos Show plus sign (+) for positive values. ios::unitbuf “Unit buffering.” The stream is flushed after each insertion. ios::stdio Synchronizes the stream with the C standard I/O system. Format fields ios::basefield ios::dec Format integral values in base 10 (decimal) (default radix).

18 Output Stream Formatting (contd.)
Student Book Output Stream Formatting (contd.) ios::stdio Format fields ios::basefield ios::dec ios::hex ios::oct ios::floatfield ios::scientific ios::fixed automatic ios::adjustfield ios::left ios::right ios::hex Format integral values in base 16 (hexadecimal). ios::oct Format integral values in base 8 (octal). ios::floatfield ios::scientific Display floating-point numbers in scientific format. Precision field indicates number of digits after the decimal point. ios::fixed Display floating-point numbers in fixed format. Precision field indicates number of digits after the decimal point. “automatic” (Neither bit is set.) Precision field indicates the total number of significant digits. ios::adjustfield ios::left Left-align values; pad on the right with the fill character. ios::right Right-align values. Pad on the left with the fill character. This is the default alignment. ios::internal Add fill characters after any leading sign or base indicator, but before the value.

19 Output Stream Formatting (contd.)
Student Book Output Stream Formatting (contd.) ios::internal Width, fill and precision int ios::width( ) int ios::width(int n) int ios::fill( ) int ios::fill(int n) int ios::precision( ) int ios::precision(int n) Width, fill and precision int ios::width( ) Reads the current width. (Default is 0.) Used for both insertion and extraction. int ios::width(int n) Sets the width, returns the previous width. int ios::fill( ) Reads the current fill character. (Default is space.) int ios::fill(int n) Sets the fill character, returns the previous fill character. int ios::precision( ) Reads current floating-point precision. (Default is 6.) int ios::precision(int n) Sets floating-point precision, returns previous precision. See ios::floatfield table for the meaning of “precision.”

20 Iostream Manipulators
Student Book Iostream Manipulators Output stream formatting can be a tedious task To make things easier to read and write, a set of manipulators are provided The manipulators are: showbase / noshowbase showpos / noshowpos uppercase / nouppercase showpoint / noshowpoint showbase / noshowbase: Indicate the numeric base (dec, oct, or hex) when printing an integral value. The format used can be read by the C++ compiler. Showpos / noshowpos: Show plus sign (+) for positive values

21 IOStream Manipulators (contd.)
Student Book IOStream Manipulators (contd.) skipws / noskipws left / right / internal scientific / fixed Some manipulators can have arguments, which require <iomanip.h> header The argument supplied manipulators are: setiosflags (fmtflags n) resetiosflags(fmtflags n) uppercase / nouppercase: Display uppercase A-F for hexadecimal values, and E for scientific values showpoint / noshowpoint: Show decimal point and trailing zeros for floating-point values. skipws / noskipws: Skip white space on input. left / right / internal: Left-align, pad on right. Right-align, pad on left. Fill between leading sign or base indicator and value. scientific / fixed: Use scientific notation setprecision( ) or ios::precision( ) sets number of places after the decimal point. setiosflags (fmtflags n) Sets only the format flags specified by n. Setting remains in effect until the next change, like ios::setf( ). resetiosflags(fmtflags n) Clears only the format flags specified by n. Setting remains in effect until the next change, like ios::unsetf( ).

22 IOStream Manipulators (contd.)
Student Book IOStream Manipulators (contd.) setbase(base n) setfill(char n) setprecision(int n) setw(int n) setbase(base n) Changes base to n, where n is 10, 8, or 16. (Anything else results in 0.) If n is zero, output is base 10, but input uses the C conventions: 10 is 10, 010 is 8, and 0xf is 15. You might as well use dec, oct, and hex for output. setfill(char n) Changes the fill character to n, like ios::fill( ). setprecision(int n) Changes the precision to n, like ios::precision(). setw(int n) Changes the field width to n, like ios::width( ).

23 Example: IOStream Manipulators
Student Book Example: IOStream Manipulators #include <fstream> #include <iomanip> void main() { ofstream trc("trace.out"); int i = 47; float f = ; char* s = "Is there any more?"; trc << setiosflags(ios::unitbuf | ios::showbase | ios::uppercase | ios::showpos); trc << i << endl; // Default to dec trc << hex << i << endl; trc << resetiosflags(ios::uppercase) << oct << i; trc.setf(ios::left, ios::adjustfield); trc << resetiosflags(ios::showbase) << dec << setfill('0'); trc << "fill char: " << trc.fill() << endl; trc << setw(10) << i << endl; Program Output: +47 0X2F 057fill char: +48 prec = 6 e+06 prec = 20

24 Example: IOStream Manipulators (contd.)
Student Book Example: IOStream Manipulators (contd.) trc << resetiosflags(ios::showpos) << setiosflags(ios::showpoint) << "prec = " << trc.precision() << endl; trc.setf(ios::scientific, ios::floatfield); trc << f << endl; trc.setf(ios::fixed, ios::floatfield); trc << setprecision(20); trc << "prec = " << trc.precision() << endl; trc << resetiosflags( ios::showpoint | ios::unitbuf); }

25 Creating Manipulators
Student Book Creating Manipulators You can create your own manipulators The manipulator may or may not have arguments The declaration for endl is ostream& endl(ostream&); cout << “howdy” << endl; the endl produces the address of that function Applicator calls the function, passing it the ostream object as an argument the endl produces the address of that function. So the compiler says “is there a function I can call that takes the address of a function as its argument?” There is a pre-defined function in Iostream.h to do this; it’s called an applicator. The applicator calls the function, passing it the ostream object as an argument. You don’t need to know how the applicator works to create your own manipulator; you only need to know the applicator exists.

26 Example: Creating Manipulators
Student Book Example: Creating Manipulators #include <iostream> ostream& nl(ostream& os) { return os << '\n'; } void main() cout << "newlines" << nl << "between" << nl << "each" << nl << "word" << nl; /* The expression os << '\n'; calls a function that returns os, which is what is returned from nl */

27 Unit Summary In this unit you have covered …
Student Book Unit Summary In this unit you have covered … Overview of the IOStream library Different features of IOStream IOStream operations & manipulators Creating custom manipulators


Download ppt "Student Book Input / Output in C++"

Similar presentations


Ads by Google