logo

UTK Notes


File Streams

Topics

Files Streams

  • We can read and write from files very similarly to reading and writing to and from the console
  • This task is called working with file streams

Files

  • Files are data stored in “secondary storage”
    • Primary storage:
      • Random Access Memory (RAM)
    • Secondary storage:
      • Hard drive
      • USB drive
      • External hard drive

Steps to Use File Streams

Working with files in C++ requires the following steps:

  1. Include the <fstream> header file
  2. Declare a file variable (ifstream for reading input or ofstream for reading output) and name the variable (i.e. fin or fout).
  3. Open the file connecting the variable to the actual file and check for failure.
  4. Do the work intended on the file (read or write) using >> or <<
  5. Close the file.
  • File Streams
    • #include <fstream>
      • Input File Stream (ifstream)
        • Data FROM DISK to RAM
      • Output File Stream (ofstream)
        • Data FROM RAM to DISK

.open()

  • Used to open BOTH input files for reading and to open output files for writing.
    • Links a stream object with a file on your file system.
    • Places a file reading marker at the beginning of the file, pointing to the first character in it.
  • If the input file doesn’t exist, it won’t be opened.
  • If you don’t have permission to open the input file, it won’t be opened.
  • If the output file does not exist, a new file with that name is created.
  • If the output file already exists, it is erased.

Input Files

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
	ifstream fin;
	fin.open("myfile.txt");
	if (!fin.is_open()) {
		cout << "Could not open file myfile.txt\n";
	}
	int data;
	fin >> data;
	cout << "File contained integer: " << data << '\n';
	fin.close();
}

.fail()

  • Returns false if the file was able to be opened
  • Returns true if it couldn’t open the file
    • Doesn’t exist
    • Don’t have permission

.is_open()

  • Returns true if the file is currently opened and linked to the file stream
  • Returns false if it couldn’t open the file
    • Doesn’t exist
    • Don’t have permission

.close()

  • De-links the file from the stream
  • ALWAYS close the file when you’re done with it.
  • Every .open() should have a matching .close().

Extraction Operator >>

  • ifstream uses the extraction operator exactly like cin.
1
2
3
4
5
6
ifstream fin;
int a, b, c;
fin.open("myfile.txt");
fin >> a >> b >> c; // Extract 3 integers from file.
cout << "I got three integers: " << a << ' ' << b << ' ' << c;
fin.close();

Line Oriented Input

  • fin >> will skip preceding whitespace and extract until the next whitespace.
  • Instead, you can grab one line at a time with getline().
  • getline(fin, line)
    • getline returns:
      • true - if it was able to get a line and put it into line
      • false - if it was not
    • getline will grab a line and put it into the string line.
    • getline strips (does NOT include) trailing newline character ‘\n

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <fstream>
using namespace std;
int main() {
	ifstream fin;
	string line;
	fin.open("myfile.txt");
	while (getline(fin, line)) {
	     cout << "Line = " << line << '\n';
	}
	fin.close();
	return 0;
}

Output File Streams

  • ofstream acts just like cout except it writes to a file, not the console.
    • Can even add formatting from iomanip!
1
2
3
4
5
6
7
ofstream fout;
int i = 10;
double j = 22.7124;
fout.open("myfile.txt"); // creates or overwrites myfile.txt
fout << left << setw(10) << i << ' ' << fixed << setprecision(2) 
     << j << '\n';
fout.close();
1
'myfile.txt' now contains: "10         22.71"

Close!!

  • An output file stream stores the data in RAM first.
    • Writing to the file is slow
    • This gives the OS time to write to the file when ready.
  • If you don’t close an output file, you’re not guaranteed the data will be written to the file!
1
2
3
4
ofstream fout;
fout.open("myfile.txt");
// ... do things with fout ...
fout.close(); // do this!!

Powerpoint