简体   繁体   中英

What's the difference between read, readsome, get, and getline?

What is the difference between these functions. When I use them they all do the same thing. For example all three calls return "hello" :

#include <iostream>
#include <sstream>

int main()
{
    stringstream ss("hello");
    char x[10] = {0};
    ss.read(x, sizeof(x));          // #1
    std::cout << x << std::endl;
    ss.clear();
    ss.seekg(0, ss.beg);
    ss.readsome(x, sizeof(x));      // #2
    std::cout << x << std::endl;
    ss.clear();
    ss.seekg(0, ss.beg);
    ss.get(x, sizeof(x));           // #3
    std::cout << x;
    ss.clear();
    ss.seekg(0, ss.beg);
    ss.getline(x, sizeof(x));       // #4
    std::cout << x << std:endl;
}

get and getline are quite similar, when get is called with parameters ( char_type* s, std::streamsize count ) . However, get reads from the stream until a delimiter is found, and then leaves it there . getline by comparison will pull the delimiter off the stream, but then drop it. It won't be added to the buffer it fills.

get looks for \\n , and when a specific number of characters is provided in an argument (say, count ) it will read up to count - 1 characters before stopping. read will pull in all count of them.

You could envisage read as being an appropriate action on a binary datasource, reading a specific number of bytes. get would be more appropriate on a text stream, when you're reading into a string that you'd like null-terminated, and where things like newlines have useful syntactic meanings splitting up text.

readsome only returns characters that are immediately available in the underlying buffer, something which is a bit nebulous and implementation specific. This probably includes characters returned to the stream using putback , for example. The fact that you can't see the difference between read and readsome just shows that the two might share an implementation on the particular stream type and library you are using.

I've observed the difference between read() and readsome() on a flash filing system.

The underlying stream reads 8k blocks and the read method will go for the next block to satisfy the caller, whereas the readsome method is allowed to return less than the request in order to avoid spending time fetching the next block.

get()和getline()之间的主要区别在于get()在输入流中保留换行符,使其成为下一个输入操作看到的第一个字符,而getline()从输入中提取并丢弃换行符。流。

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