About reading from file to string

Any possible problems with this code?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main()
{
	std::fstream in("file.txt", std::ios::in);
	in.seekg(0, std::ios::end);
	std::size_t len = in.tellg();
	in.seekg(0, std::ios::beg);
	std::string outName;
	outName.resize(len);
	in.read(&outName[0], outName.size());
	in.close();
	std::cout << outName.c_str() << std::endl;

	return 0;
}
There is a portability problem with using seekg/tellg on files open in text mode: this does not necessarily return the same number as the number of characters you would read from the file. Use binary mode if you want to deal with file sizes.

it's more idiomatic to let the string grow as needed, since disk I/O is usually slower than log(size) memory allocations.

1
2
3
4
5
6
7
8
9
#include <iterator>
#include <fstream>
#include <string>
int main()
{
    std::ifstream in("file.txt");
    std::istreambuf_iterator<char> beg(in), end;
    std::string outName(beg, end);
}

or with a loop
Last edited on
Topic archived. No new replies allowed.