CIS 250 - File I/O
Objectives
- use C++ text file I/O
- use C++ binary file I/O
File I/O - text
- steps to using a file in C++:
- include fstream header file
- declare file stream variables
- associate variable with I/O sources
- use variables with >>, <<, and other functions
- close the streams
- #include <fstream>
- declaring an input file variable: ifstream ifile;
- opening an input file: ifile.open("myfile"); (file must exist)
- combining declaration and opening: ifstream ifile("myfile");
- output works much like input: ofstream ofile("myfile");
- opening an output file for appending: ofile.open("myfile", ios::app); (file must exist)
- use standard stream operators and functions:
- ofile << num1 << " " << num2 << endl;
- ifile >> num1 >> num2;
- close fstreams when done: ifile.close()
- check for open failure: if (!ifile)
- check for end of file input: while (ifile)
- see fileio1.cpp for some sample file I/O code
File I/O - binary
- specify binary when opening file: ofstream ofile("testfileio2.txt", ios::binary);
- use write function to write data: ofile.write(reinterpret_cast<char *>(&n),
sizeof(n));
- use read function to read data: ifile.read(reinterpret_cast<char *>(&n),
sizeof(n));
- seek to end of file (reading): ifile.seekg(0L, ios::end);
- seek to beginning of file (reading): ifile.seekg(0L, ios::beg);
- seek 10 bytes further relative to current position (reading): ifile.seekg(10L, ios::cur);
- get postion in file (reading): ifile.tellg()
- position at end of file is length in bytes
- determine number of records by dividing file size by record size
- seekp and tellp are for write pointer
- see fileio2.cpp for some sample binary file I/O code
- see fileio3.cpp for some sample random access file I/O code