Re: Standard C++ file size???
On Oct 5, 10:54 pm, "Peter Olcott" <NoS...@SeeScreen.com> wrote:
"Victor Bazarov" <v.Abaza...@comAcast.net> wrote in message
news:gcaphr$8km$2@news.datemas.de...
Peter Olcott wrote:
Is there any standard C++ way to determine the size of a
file before it is read?
No. The "standard C++ way" is to open the file for
reading, seek to the end of the file and get the position.
My best guess is that this is exactly what I need. I want to
read in an ASCII text file into a single contiguous block of
memory.
It would seem that I could do this using the method you
propose, and use a std::vector<unsigned char> for the memory
block, resized to position + 1. I would also guess that this
same method may also work for any possible type of data. Of
course I am assuming that the data is being read in binary
mode, in each case.
In this case you don't need to know the size. It could be as simple
as:
#include <fstream>
#include <iterator>
#include <vector>
int main()
{
std::ifstream file("text.file");
std::vector<char> file_in_memory(
(std::istream_iterator<char>(file))
, (std::istream_iterator<char>())
);
// the file has been read into file_in_memory
}
However, if performance is paramount, or you need to know the exact
file errors, or the file is too big to fit into memory, you may like
to use your platform's native functions (like POSIX open(), fstat()
and mmap()).
--
Max