C++ Logo

STD-PROPOSALS

Advanced search

Subject: [std-proposals] filestream read to string
From: Ed Bird (HYPER-NOVA_at_[hidden])
Date: 2019-12-24 13:56:30


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?

Similar suggestions could be made in reverse - initializing a std::ofstream with a std::string to write to file, or possibly better introducing a member to std::string which takes a filename as a std::string or char* as argument and writes the current contents of the string to that filename.

eg

        std::ofstream ofile("filename", string_buffer); // write contents of string_buffer to file "filename"

or

        std::string::write_to_file("file.txt");

Best Regards,
Ed



STD-PROPOSALS list run by std-proposals-owner@lists.isocpp.org

Standard Proposals Archives on Google Groups