Here is my code
std::ifstream myfile;
std::string line;
long begin,end;
myfile.open("c:\\IPlog.txt");
if (myfile.is_open())
{
while (! myfile.eof() )
{
std::getline (myfile,line);
std::cout << line << std::endl;
}
myfile.seekg(0);
begin = myfile.tellg();
myfile.seekg (0, std::ios::end);
end = myfile.tellg();
std::cout << "size is: " << (end-begin) << " bytes.\n";
myfile.close();
}
I only want to open the file once and get the file size then get the
contents.
Trouble is by getting to eof with extracting file contents how do I then get
back to the beginning of the file. I thought myfile.seekg(0); did that?
Angus
The easiest way would be to get the size first and read the content
later. The problem you are having is that EOF is a flag set and all the
seek()ing in the world wont change that, you first have to clear the
flag, do this by calling the clear() method.
--
Erik Wikström
The condition for the while loop is almost certainly not what you need.
eof() is only set *after* a read has failed. Your loop will probably
output the last line twice. See:
http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.5
You want to use the return value of getline() as your loop condition,
like:
while (std::getline(myfile, line)) {
std::cout << line << std::endl;
}
> myfile.seekg(0);
> begin = myfile.tellg();
>
> myfile.seekg (0, std::ios::end);
> end = myfile.tellg();
>
> std::cout << "size is: " << (end-begin) << " bytes.\n";
>
> myfile.close();
> }
>
> I only want to open the file once and get the file size then get the
> contents.
>
> Trouble is by getting to eof with extracting file contents how do I then get
> back to the beginning of the file. I thought myfile.seekg(0); did that?
Once you've hit EOF, you need to clear() the ifstream before you can
really do much else with it.
Also, note that there is no reliable, portable way to get the filesize
in Standard C++. However, please see the thread I started last week
regarding a file read progress indicator, maybe it will give you some
ideas:
http://groups.google.com/group/comp.lang.c++/browse_thread/thread/d6f8ed63cab395e2/
--
Marcus Kwok
Replace 'invalid' with 'net' to reply
This simple example extracts the contents of the file into
a stringbuf in a single operation. You can then obtain the
size of the string by calling size(). Note that the file
size and the length of the string might differ depending
on the newline convention used by the OS (e.g., CR-LF on
Windows, and LF on UNIX).
I tested the code with the Apache C++ Standard Library but
it should work just the same with other implementations.
#include <fstream>
#include <iostream>
#include <sstream>
int main ()
{
std::stringbuf sb;
std::ifstream in (__FILE__);
in >> sb;
std::string data = sb.str ();
std::cout << "File size: " << data.size () << '\n'
<< "File contents:\n"
<< data << '\n';
}
This simple example extracts the contents of the file into