L11 C++ IO

#ece244

Dynamically allocating an array of pointers is a lot more memory efficient than an array of objects

8 bytes per address (pointer), much more efficient than an object (probably more than 8 bytes)


File IO using ifstream and ofstream

example: program that writes to a file

#include <iostream>
#include <fstream>
int main(void) {
	// file output
	ofstream outFile("File.txt");
	// ofstream is the class name
	// outFile is our own name for the object
	
	outFile << "Hello" << endl;
	outFile.close(); // saves to the file
	// once we close, we cannot write to the file again
	
	return 0;
}
Usage of ofstream

When a file is called using ofstream:

  • If file does not exist, it will be created
  • If file exists, the content inside will be overwritten
  • If file exist, and we want to append to content:
    ofstream outFile("file.txt", ios::app);
    

example: read from an input file

	#include <fstream>
	using namespace std;
	int main(void) {
		ifstream inFile("inFile.txt");
		// creates object inFile and opens file inFile.txt
		
		// or we can seperate them:
		ifstream inFile;
		inFile.open("inFile.txt");
		
		int num1, num2;
		inFile >> num1 >> num2; // reading two integers from inFile
		cout << "Sum is " << num1 + num2 << endl;
	}

working with other directories

Everything is a relative path from the current directory


buffering

It is slow to write output to a file/terminal compared to writing it in a "buffer"

flushing from buffer (output)

flushing from buffer (input)

int x, y;
cin >> x >> y;
input is 13 4\n

problem with the above example

if input is instead 13.4\n:

what should you do before taking input?

  1. Always check if the fail flag is raised when taking input
  2. If fail flag is raised, then handle the error

To check if a fail flag is raised:

if (inputFile.fail()) {
	cerr << "Cannot" << endl;
	return 1; // return 1 
}

Note: cerr is an output stream similar to cout, but it is unbuffered, so it shows up immediately in terminal.

Then, handle the error: