How to copy a certain number of chars from a file to a vector the STL-way?

前端 未结 5 814
不知归路
不知归路 2020-12-11 05:27

If I want to copy the contents of a file to a vector, I can do it like that:

std::ifstream file(\"path_to_file\");
std::vector buffer(std::istrea         


        
5条回答
  •  北海茫月
    2020-12-11 05:54

    Credit due to @sbi, I forgot about generate_n.

    The streambuf inside file has a function snextc which returns the next character, qualifying it as a generator function, once its implicit this argument is bound.

    generate_n( back_inserter( buffer ), 42,
                tr1::bind( tr1::mem_fn( &streambuf::snextc ), file.rdbuf() ) );
    

    For vector, just read directly. This is good for deque or whatever.

提交回复
热议问题