1 / 7

Mastering File Input and Output with fstream in C++

Learn how to efficiently handle file operations in C++ using the fstream library. This guide covers opening, reading, writing, and closing files with detailed examples and explanations.

eherman
Download Presentation

Mastering File Input and Output with fstream in C++

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. C++ FileIO pepper

  2. fstream fstream From http://www.cs.uic.edu/~jbell/CourseNotes/CPlus/FileIO.html

  3. Using fstream • Include <fstream> • Declare variable of type fstream • Open file – ask your fstream variable to open the file • Your ofstreamvar .open(“filename”,qualifiers) • qualifiers • In: ios::in • Out: ios::out • Append: ios::append • Binary: ios::binary • Ex: • ofstreammyfile; • myfile.open ("example.bin", ios::out | ios::app | ios::binary);

  4. Test status of stream • myfile.is_open() : returns true if open • myfile.eof() : returns true if file at end and open for reading • myfile.bad() : return true if any read or write fails • myfile.good() : opposide of bad • Ex: If (myfile.is_open()) { myfile << “ I can write just like cout “;} If (!myfile.eof()) { // read more };

  5. Stream positions • directions: • ios::beg (beginning of file) • ios::cur (current position) • ios::end (end of file)

  6. Binary file methods • binary read and write helper: • read (buf, size); • write(buf, size); • Just makes it easier to use a record layout (structure)

  7. Close when done • Ask your stream to close itself: • myfile.close();

More Related