File input and output

File IO

To read and write to and from files we use streams located in the <fstream> header.

Input

To read a file we use the ifstream from the <fstream> header. The ifstream has a constructor that specifies the file name for reading:

#include <iostream>
#include <fstream>
int main(){
	std::ifstream is("inputfile.txt"); // open file for reading
}

To read a (text) file one word at the time we use the stream extraction >> operator:

#include <iostream>
#include <fstream>
#include <string>
int main(){
	std::string tempstring;
	std::ifstream is("inputfile.txt");
	while (is >> tempstring){
		std::cout << tempstring << ' ';
	}
}

To read a file content into multiple variables we use multiple stream extraction >> operators:

#include <iostream>
#include <fstream>
#include <string>
int main(){
	std::string tempstring;
	int x;
	double d;
	std::ifstream is("inputfile.txt");
	while (is >> tempstring >> x >> d){
		std::cout << tempstring << ' ' << x << ' '<< d;
	}
}

To read a file one line at the time (line by line) we use the std::getline() function:

#include <iostream>
#include <fstream>
#include <string>
int main(){
	std::string tempstring;
	std::ifstream is("inputfile.txt");
	while (std::getline(is, tempstring)){
		std::cout << tempstring << std::endl;
	}
}

Output

To write to a file we use the ofstream from the <fstream> header. The ofstream has a constructor that specifies the file name for the output:

#include <iostream>
#include <fstream>
int main(){
	std::ofstream os("outputfile.txt"); // open file for writing
}

To write to a file we use the insertion operator <<:

#include <iostream>
#include <fstream>
int main(){
	std::ofstream os("outputfile.txt"); // open file for writing
	os << "Hello World!"; // writes Hello World! to our file
}

To write multiple lines of text use a new-line character \n:

#include <iostream>
#include <fstream>
int main(){
	std::ofstream os("outputfile.txt"); // open file for writing
	os << "Hello World!" << '\n';
	os << "Line number 2." << '\n';
}

To write variables to a (text) file simply use multiple << operators:

#include <iostream>
#include <fstream>
int main(){
	int x = 123;
	char c = 'A';
	double d = 456.78;
	std::ofstream os("outputfile.txt"); // open file for writing
	os << x << ' ' << c << ' ' << d ;
}