70 likes | 79 Views
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.
E N D
C++ FileIO pepper
fstream fstream From http://www.cs.uic.edu/~jbell/CourseNotes/CPlus/FileIO.html
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);
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 };
Stream positions • directions: • ios::beg (beginning of file) • ios::cur (current position) • ios::end (end of file)
Binary file methods • binary read and write helper: • read (buf, size); • write(buf, size); • Just makes it easier to use a record layout (structure)
Close when done • Ask your stream to close itself: • myfile.close();