Search code examples
c++istream

Why does std::istream::ignore discard characters?


On the CPlusPlus website for std::istream::ignore, it says

istream& ignore (streamsize n = 1, int delim = EOF);

Extract and discard characters

Extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim.

Why does it say it discards them rather than returns them?

EDIT

As requested, here is the particular code in question. It is a callback function, server-side, processing the client file that was sent (_data)

static void loadFile (const std::string &_fileName, std::vector<char> &_data)                                                                                            
{
    std::ifstream ifs;
    ifs.exceptions(std::ifstream::failbit);
    ifs.open(_fileName, std::ifstream::in | std::ifstream::binary);
    auto startPos = ifs.tellg();
    ifs.ignore(std::numeric_limits<std::streamsize>::max());
    auto size = static_cast<std::size_t>(ifs.gcount());
    ifs.seekg(startPos);
    _data.resize(size);
    ifs.read(_data.data(), size);
    std::cout << "loaded " << size << " bytes" << std::endl;
}   

Solution

  • auto startPos = ifs.tellg();
    

    This stores the position at the beginning of the (just-opened) file.

    ifs.ignore(std::numeric_limits<std::streamsize>::max());
    

    This reads through the entire file (until EOF) and discards the content read.

    auto size = static_cast<std::size_t>(ifs.gcount());
    

    gcount returns the number of characters read by the last unformatted input operation, in this case, the ignore. Since the ignore read every character in the file, this is the number of characters in the file.

    ifs.seekg(startPos);
    

    This repositions the stream back to the beginning of the file,

    _data.resize(size);
    

    ...allocates enough space to store the entire file's content,

    ifs.read(_data.data(), size);
    

    and finally reads it again into _data.