- Use C++ text file I/O
- Use C++ binary file I/O
- 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
- 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()
- The position at the end of file is the length of the file in bytes
- Determine number of records by dividing file size by record size
- seekg and tellg are for the read pointer (the g stands for "get")
- seekp and tellp are for the write pointer (the p stands for "put")
- See fileio2.cpp for some sample binary file I/O code
- See fileio3.cpp for some sample random access file I/O code