C++ Read Entire Text File

徘徊边缘 提交于 2019-12-11 06:07:26

问题


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


回答1:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/15547645/c-read-entire-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!