fstream (file stream)

https://www.youtube.com/watch?v=XJhIJ6J5obY <<< on the basics

https://youtu.be/P7XGOBoVzW4 <<< on storing objects

Include

#include <fstream>

Instantiate class

std::fstream file;   // default:  ios :: in | ios :: out 

std::ofstream file;  // default:  ios :: out

std::ifstream file;  // default:  ios :: in

Open

file.open(fileName, openMode);

// example
file.open("file.txt", std::ios :: in);

// you can have multiple openModes
file.open("file.txt", std::ios :: in | std::ios :: out | std::ios :: trunc);

// IF WORKING WITH OBJs
file.open("file.bin" std::ios :: binary)

Read and Write

// write
file << "string of words";
file << "string of words" << endl;

// read
file >> varName;
getline(file, varName);

while(getline(file, varName)) // will loop, space separated
while(file >> varName)  // will loop, enter separated

Read and Write Objects

https://youtu.be/P7XGOBoVzW4 <<< watch that its very good

// --- WRITE ---
// we need to specify
// (what we want to write, the size of the class)
// note we cast the Object into a char
file.write((char *)&objectName, sizeof(className));

// --- READ ---
// sets read (get) pointer at the start of the file
file.seekg(0);

// must instanciate an empty object
className newObjName;
// (obj to be read to, how may bits to read)
file.read((char *)&newObjName, sizeof(className));

Close

// closes the link, note object is not destroyed, 
// content remains (text can still be read)
file.close();

// emptys the contents of file, so if its a text file, there will be no text
file.clear();

Functions

file.is_open() // returns true, if file is open

file.fail()    // returns true, if file failed to open

Simple .txt Example

// create object
ifstream inFile;
inFile.open("file.txt");

// checks for fail
if (inFile.fail()) 
	cout << "failed to open" << endl;

else
{
	string s;
	// note: strings end at a space
	// to read line by line use
	// while(getline(inFile, s))
	while (inFile >> s)
		cout << s << endl;
	
	inFile.close();
	inFile.clear();
}