fbpx

C++: File Input/Output

Bjarne-stroustrup
 

In this task, the job is to create a file called “output.txt”, and place in it the contents of the file “input.txt”, via an intermediate variable. In other words, your program will demonstrate: (1) how to read from a file into a variable, and (2) how to write a variable’s contents into a file. Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
	string line;
	ifstream input ( "input.txt" );
	ofstream output ("output.txt");

	if (output.is_open()) {
		if (input.is_open()){
			while (getline (input,line)) {
				output << line << endl;
			}
			input.close(); // Not necessary - will be closed when variable goes out of scope.
		}
		else {
			cout << "input.txt cannot be opened!\n";
		}
		output.close(); // Not necessary - will be closed when variable goes out of scope.
	}
	else {
		cout << "output.txt cannot be written to!\n";
	}
	return 0;
}

Simpler version:

#include <iostream>
#include <fstream>
#include <cstdlib>

int main()
{
	std::ifstream input("input.txt");
	if (!input.is_open())
	{
		std::cerr << "could not open input.txt for reading.\n";
		return EXIT_FAILURE;
	}

	std::ofstream output("output.txt");
	if (!output.is_open())
	{
		std::cerr << "could not open output.txt for writing.\n";
		return EXIT_FAILURE;
	}

	output << input.rdbuf();
	if (!output)
	{
		std::cerr << "error copying the data.\n";
		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}

Using istream- and ostream- iterators:

# include <algorithm>
# include <fstream>
 
int main() {
  std::ifstream ifile("input.txt");
  std::ofstream ofile("output.txt");
  std::copy(std::istreambuf_iterator<char>(ifile),
            std::istreambuf_iterator<char>(),
            std::ostreambuf_iterator<char>(ofile));
}

Even simpler way:

#include <fstream>

int main()
{
	std::ifstream input("input.txt");
	std::ofstream output("output.txt");
	output << input.rdbuf();
}

SOURCE

Content is available under GNU Free Documentation License 1.2.