Given:
const string inputFile = "C:\MyFile.csv";
char buffer[10000];
How do I read the chars of the file in to the above buffer? I have been looking around online but none of the answers seem to work. They all wish to call getline().
Given:
const string inputFile = "C:\MyFile.csv";
char buffer[10000];
How do I read the chars of the file in to the above buffer? I have been looking around online but none of the answers seem to work. They all wish to call getline().
Another option would be to use a
std::vector
for the buffer, then use astd::istreambuf_iterator
to read from anstd::ifstream
directly into thestd::vector
, eg:Alternatively:
If you go with @user4581301's solution, I would still suggest using
std::vector
for the buffer, at least:If you're concerned with efficiency (you rejected
getline()
) then a C-stylemmap
is probably best:Most of the time they are right about
getline
, but when you want to grab the file as a stream of bytes you want ifstream::read.Docs for ifstream::seekg
Docs for ifstream::tellg
NOTE:
seekg
andtellg
to get the size of the file falls into the category of "usually works". This is not guaranteed.tellg
only promises a number that can be used to return to a particular point. That said,Note: The file was not opened in binary mode. There can be some behind-the-scenes character translations, for example the Windows newline of
\r\n
being converted to the\n
used by C++.length
can be greater than the number of characters ultimately placed inbuffer
.2019 rethink
If you're looping on buffered reads until you consume the whole file you'll want some extra smarts to catch that.
If you want to read the whole file in one shot and can afford to use resizable buffers, take the advice in Remy Lebeau's answer.