1

i try to read the entire text file using vc++ with this code

ifstream file (filePath, ios::in|ios::binary|ios::ate);
    if (file.is_open())
    {
        size = (long)file.tellg();
        char *contents = new char [size];
        file.seekg (0, ios::beg);
        file.read (contents, size);
        file.close();
        isInCharString("eat",contents);

        delete [] contents;
    }

but it's not fetch all entire file ,why and how to handle this?

Note : file size is 1.87 MB and 39854 line

HokaHelal
  • 1,568
  • 2
  • 15
  • 20
  • See the following page http://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring – woosah Mar 21 '13 at 12:35
  • possible duplicate of [What is the best way to slurp a file into a std::string in c++?](http://stackoverflow.com/questions/116038/what-is-the-best-way-to-slurp-a-file-into-a-stdstring-in-c) – Konrad Rudolph Mar 21 '13 at 13:24

4 Answers4

2

You are missing the following line

file.seekg (0, file.end);

before:

size = file.tellg();
file.seekg (0, file.beg);

As discribed in this example: http://www.cplusplus.com/reference/istream/istream/read/

2

Another way to do this is:

std::string s;
{
    std::ifstream file ("example.bin", std::ios::binary);
    if (file) {
        std::ostringstream os;
        os << file.rdbuf();
        s = os.str();
    }
    else {
        // error
    }
}

Alternatively, you can use the C library functions fopen, fseek, ftell, fread, fclose. The c-api can be faster in some cases at the expense of a more STL interface.

Pete
  • 4,598
  • 20
  • 30
0

You really should get the habit of reading documentation. ifstream::read is documented to sometimes not read all the bytes, and

   The number of characters successfully read and stored by this function 
   can be accessed by calling member gcount.

So you might debug your issues by looking into file.gcount() and file.rdstate(). Also, for such big reads, using (in some explicit loop) the istream::readsome member function might be more relevant. (I would suggest reading by e.g. chunks of 64K bytes).

PS it might be some implementation or system specific issue.

Basile Starynkevitch
  • 1
  • 16
  • 251
  • 479
0

Thanks all, i found the error where, simply the code below reads the entire file , the problem was in VS watcher itself it was just display certain amount of data not the full text file.

HokaHelal
  • 1,568
  • 2
  • 15
  • 20