Subject: [std-proposals] filestream read to string
From: Ed Bird (HYPER-NOVA_at_[hidden])
Date: 2019-12-24 13:56:30
I think it is probably likely that this proposal has been suggested before, however -
I frequently find myself writing (exactly) the following code
std::ifstream ifile(file_name, std::ios::ate);
std::size_t ifile_size = ifile.tellg();
char *buffer = new char[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.
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
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.
std::ofstream ofile("filename", string_buffer); // write contents of string_buffer to file "filename"
STD-PROPOSALS list run by firstname.lastname@example.org
Standard Proposals Archives on Google Groups