C++ Read Entire Text File

2019-08-09 22:41发布

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

4条回答
Melony?
2楼-- · 2019-08-09 23:14

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/

查看更多
Bombasti
3楼-- · 2019-08-09 23:18

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.

查看更多
Explosion°爆炸
4楼-- · 2019-08-09 23:25

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.

查看更多
再贱就再见
5楼-- · 2019-08-09 23:28

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.

查看更多
登录 后发表回答