1 / 19

Streams

Streams. In C++, I/O occurs in streams. A stream is a sequence of bytes flowing from a source to a destination. Streams are typically associated with I/O devices. Examples: A file stream is an object that allows interaction with files.

Télécharger la présentation

Streams

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. Streams • In C++, I/O occurs in streams. • A stream is a sequence of bytes flowing from a source to a destination. • Streams are typically associated with I/O devices. • Examples: • A file stream is an object that allows interaction with files. • cout is a predefined output stream that "transfers" bytes from the program to the device associated with standard output • The iostream library provides input and output functionality using streams.

  2. cin • cin is an object of type istream (input stream), associated with the standard input device (the keyboard). • Use the stream extraction operator (>>) to extract bytes from the input stream and into a variable int value; cin >> value; int amount; double tax; cin >> amount >> tax; this is equivalent to cin.operator<<(value);

  3. cout • cout is an object of type ostream (output stream), associated with the standard output device (the monitor). • Use the stream insertion operator << to insert bytes from the variable to the output stream. int value = 5; cout << value; int amount = 40; double tax = 8.2; cout << amount << tax;

  4. type-safe I/O • << and >> are overloaded to accept data of different types: • If unexpected data is processed, an error bit is set. • You can check the values of the error bits to see if I/O was successful • You can also discard incorrect characters, in case of an error int value = 5; char *str = "Hello"; char c = ' ' cout << value << c << str;

  5. error bits • eofbit • An input operation reached the end of the input sequence • This bit is set when an attempt is made to read past the end of file. • failbit • An input or output operation failed to read/write the expected item. For example, cin expected to read a double but found a char instead. Or, stream could not be opened at all. • badbit • An error occurred that resulted in loss of data. A possible cause for this might be memory shortage. • goodbit • Everything is fine. This bit is 1 as long as all of the above are 0.

  6. error bits • There are several member functions that allow you to check the error state: • bool eof() • True if the eofbit is set, false otherwise • bool fail() • True if the failbit or badbit is set, false otherwise • bool bad() • True if the badbit is set, false otherwise • bool good() • True if no error bit is set, false otherwise

  7. error bits • iostate rdstate() • This function returns the current status of the error flags. • Example: • void clear() • This function restores a stream's state to good. if (cin.rdstate() == ios::goodbit) cout << "Everything is fine" << endl; if (cin.rdstate() == ios::eofbit) cout << "End of file" << endl;

  8. cin/cout vs. file I/O • The ostream and istream objects cout and cin are predefined and associated with the standard output and input devices. • In order to read from or write to a file we must manually associate it with an input or output file stream object. • We must include the fstream header file for file I/O

  9. Sequential files • Sequential file = a file containing a collection of data. • C++ regards the file as a sequence of bytes. • We regard the file as a sequence of records in some specific order and write code to handle the file according to our view of its organization.

  10. Sequential files • In order to open a file for input or output, we must first create an ifstream or ofstream object and then associate the file with that object: ifstream inFile; // declare an ifstream object ofstream outFile; // declare an ofstream object inFile.open("data.txt", ios::in); // associate file data.txt (in the // current directory) with inFile // and open it for input. outFile.open("results.txt", ios::out); // associate file results.txt (in // the current directory) with // outFile and open it for output.

  11. Sequential files • More examples: • If results.txt already exists, ios::app means we will append to it, whereas ios::out means it will be cleared first. fstream inOutFile; // declare an fstream object ofstream outFile; // declare an ofstream object inOutFile.open("data.txt", ios::in | ios::out); // associate file data.txt // with inOutFile and open // it for both input & output outFile.open("results.txt", ios::app); // associate file results.txt with // outFile and open it for output.

  12. File I/O • You may use the stream insertion and extraction operators to write to or read from a sequential file. • For user-defined types, the stream insertion and extraction operators must be overloaded accordingly. ofstream outFile; outFile.open("grades.txt", ios::out); char *name = "John Smith"; double grade = 98.8; outFile << name << " " << grade << endl;

  13. File I/O • Close the file stream when you don't need the file any longer (if you don't, it will be closed automatically via its destructor when it goes out of scope) ofstream outFile; outFile.open("grades.txt", ios::out); char *name = "John Smith"; double grade = 98.8; outFile << name << " " << grade << endl; outFile.close();

  14. operator>> and whitespace • operator>> ignores whitespace: • What if we want to read the whitespace as well? • Use the get() function fstream iofile("test.txt", ios::in|ios::out); iofile << 'a' << ' ' << 'b'; iofile.seekp(0); char x, y; iofile >> x >> y; // here, x is 'a' and y is 'b'. The empty space between them // has been skipped.

  15. get() • Use #1 : with no arguments • ch = inFile.get() ; // reads one character and assigns it to ch • Use #2 : with one argument • inFile.get(ch); // reads one character and assigns it to ch fstream iofile("test.txt", ios::in | ios::out); iofile << 'a' << ' ' << 'b'; iofile.seekp(0); char x, y; iofile >> x >> y; // here, x is 'a' and y is 'b'

  16. put(), getline() • put() is similar to get() but is used for writing a single character • getline(char array, size, delimiter)reads size-1 characters or until the delimiter is found and places the result in the char array (the array will be null terminated). • It is used to read whole lines.

  17. peek(), seekg(), seekp() • inFile.peek() is used to look at the next character in the stream without actually removing it from the stream • inFile.seekg(n)moves the get pointer to the nth byte from the beginning of the file • outFile.seekp(n)moves the put pointer to the nth byte from the beginning of the file

  18. Unformatted I/O • To read or write raw bytes, use the read() and write() functions. • outFile.write(buffer, n) writes n bytes from buffer to outFile. • buffer must be the address of a string. If it is not, typecast it accordingly. • inFile.read(buffer, n) reads n bytes from inFile and places them in buffer. • buffer must be the address of a string. If it is not, typecast it accordingly.

  19. binary mode • In many cases we want to open a file in binary mode. • Possible reasons: • Text files are represented differently in different systems and we want to avoid related peculiarities. • Applications such as compression require it. • To process a file in binary mode we must open it with ios::binary • In that mode, << and >> do NOT work properly. Instead use read() and write().

More Related