Reading a certain number of characters from a C ++ stream in std :: string

I am very familiar with most C ++, but one area that I avoided was the input / output stream, mainly because I used it on embedded systems where they do not fit. I had to meet them recently, but I'm struggling to figure out how I feel should be simple.

I am looking for a relatively efficient way to read a fixed number of characters from a C ++ stream in std::string. I could easily read the temporary array charusing the method read()and convert it to std::string, but it is pretty ugly and includes a wasteful copy. I could also read the entire stream into a string with something like this:

std::string getFile(std::fstream &inFile)
{
    std::stringstream buffer;
    buffer << inFile.rdbuf();
    return buffer.str();
}

... But unlimited reading into memory is usually a bad idea, so I would really like to access the file one block at a time, say, 4K or so. I could also read the character at a time, but it just seems more ugly and less efficient than reading into a temporary array char.

So, is there an easy way to get std::stringdirectly from a stream that contains the following N characters from the stream? It is possible that there is no easy way to do this, but it seems strange to me that this will be absent, so I felt that I was missing something obvious.

, API- C , , . - read() write(), , , , .

+5
1

.:)

mystring.resize( 20 );
stream.read( &mystring[0], 20 );

Edit:

++ 11. . data() c_str(), std::string::operator[] .

++ 03, , std::string , . ++ 03 , , - - .

+8

All Articles