Skip to content

Filestream

MarJC5 edited this page Oct 28, 2022 · 1 revision

Opening a File

A file must be opened before you can read from it or write to it. Either ofstream or fstream object may be used to open a file for writing. And ifstream object is used to open a file for reading purpose only.

  • An istream object represents a file input stream so you can only read it
  • An ofstream object represents a file output stream that you can only write to it
  • An fstream is a file stream that you can read or write

Writing to a File

Write information to a file from the program using the stream insertion operator (<<).

Reading from a File

Read information from a file into the program using the stream extraction operator (>>).

int main()
{
	//ifstream: input file stream
	std::ifstream	ifs("numbers");
	unsigned int	dst;
	unsigned int	dst2;
	ifs >> dst >> dst2;

	std::cout << dst << " " << dst2 << std::endl;
	ifs.close();

	//-------------------------
	//ofstream: output file stream
	std::ofstream	ofs("test.out");
	ofs << "i like ponies a whole damn lot" << std::endl;
	ofs.close();
	return (0);
}
Clone this wiki locally