C++ Logo

std-proposals

Advanced search

Re: filestream read to string

From: Magnus Fromreide <magfr_at_[hidden]>
Date: Wed, 25 Dec 2019 01:04:32 +0100
On Tue, Dec 24, 2019 at 07:56:30PM +0000, Ed Bird via Std-Proposals wrote:
> Hi all,
>
> I think it is probably likely that this proposal has been suggested before, however -
>
> I frequently find myself writing (exactly) the following code
>
> std::string file_name("file.txt");
> std::ifstream ifile(file_name, std::ios::ate);
> std::size_t ifile_size = ifile.tellg();
> ifile.seekg(0, std::ios::beg);
> char *buffer = new char[ifile_size];
> ifile.read(buffer, ifile_size);
>
> Essentially, open a file, and read its contents into a char buffer.
>
> Occasionally this is accompanied by converting the char buffer into a string.
>
> std::string buf(buffer)
>
> I am not an expert, however my understanding is that ifstream uses some kind of underlying buffer, which has some (presumably fixed) size and this is used to buffer data from disk.
>
> My suggestion would be to either introduce an fstream member function which when called causes the entire contents of the disk to be stored in the buffer, along with some raw access to this buffer.
>
> Alternatively, the following suggestion may be more elegant.
>
> Allow initialization of a string with an ifstream object, for example
>
> std::string(std::ifstream("file.txt"));
>
> Which would read the contents of file.txt into the string.
>
> I realize this may have been suggested before. If so my apologies for this. Perhaps there is a reason not to implement such a feature?

Is the following C++98-code acceptable for the string case:

std::ifstream ifs("file.txt");
std::string buf(std::istream_iterator(ifs), std::istream_iterator());

/MF

Received on 2019-12-24 18:07:04