How to use fstream for creating a file?

Oct 27, 2016 at 10:05am
Hi,

I have read several reference articles regarding file IO, and about opening files in particular, but nowhere found any info about how to distinguish (with combinations of open mode flags) between the cases when file should be created if not exist during opening, and when function must fail if the file doesn't exist. Could someone quote the link where this is described.

Thanks.

nbd
Oct 27, 2016 at 10:17am
Instead of fstream I find it easier to use ofstream when writing (creating) files and ifstream when reading from files.

If you use ofstream it will automatically create a new file if it doesn't exist.

1
2
3
4
5
6
7
8
9
#include <fstream>

int main()
{
	std::ofstream file("test.txt");
	
	// For text files you write output the same way as with std::cout.
	file << "Hello 123!\n";
}


It will never create a new file when using ifstream.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <fstream>
#include <string>

int main()
{
	std::ifstream file("test.txt");
	
	if (!file)
	{
		std::cout << "File not found!";
		return 1;
	}
	
	// For text files you read input the same way as with std::cin.
	std::string line;
	while (std::getline(file, line))
	{
		std::cout << line << '\n';
	}
}
Last edited on Oct 27, 2016 at 10:21am
Oct 27, 2016 at 10:24am
Many thanks, Peter. Of course internet search returns plenty of links on programming forums and stack overflow with users' advises on this subject. I wonder where this is described in official docs or in reference articles on this site?

Thanks.

nbd
Oct 27, 2016 at 11:10am
Look at the the documentation for the constructors that take a string as argument.

http://en.cppreference.com/w/cpp/io/basic_ofstream/basic_ofstream
http://en.cppreference.com/w/cpp/io/basic_ifstream/basic_ifstream
http://en.cppreference.com/w/cpp/io/basic_fstream/basic_fstream

It describes what flags will be used by default and how they are passed on to std::basic_filebuf::open.

http://en.cppreference.com/w/cpp/io/basic_filebuf/open

There you find a table that describes what will happen for various flag combinations when the file doesn't exist.
Last edited on Oct 27, 2016 at 11:11am
Oct 27, 2016 at 11:18am
Thanks! I was just a bit perplexed when I didn't found this important information on this site. Will be checking both sites from now on.
Topic archived. No new replies allowed.