HokaHelal
HokaHelal

Reputation: 1568

C++ Read Entire Text File

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

Upvotes: 1

Views: 5924

Answers (4)

HokaHelal
HokaHelal

Reputation: 1568

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.

Upvotes: 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.

Upvotes: 0

Pete
Pete

Reputation: 4812

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.

Upvotes: 2

Philipp Michalski
Philipp Michalski

Reputation: 606

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/

Upvotes: 2

Related Questions