简体   繁体   中英

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;
}   

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

Because there are other functions to return them. Seestd::istream::getline and std::getline


Update

The whole purpose of the following lines in your updated post is to obtain the size of the file.

auto startPos = ifs.tellg();
ifs.ignore(std::numeric_limits<std::streamsize>::max());
auto size = static_cast<std::size_t>(ifs.gcount());

This is the first time I have seen use of istream::ignore() to do that. You could also use the following to get the size of the file.

// Find the end of the file
ifs.seekg(0, std::ios::end);

// Get its position. The returned value is the size of the file.
auto size = ifs.tellg();
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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM