简体   繁体   中英

ostream_iterator to a string instead of cout?

someone just helped me get a filename from a directory with boost using

    if (exists(p))    // does p actually exist?
    {

        if (is_directory(p))      // is p a directory?
        {
            copy(directory_iterator(p), directory_iterator(), // directory_iterator::value_type
                ostream_iterator<directory_entry>(cout, "\n")); // is directory_entry, which is

        }
    }

but I want it in a string not cout

how can i capture that copy?

You can copy the content to a std::ostringstream and retrieve a copy of the buffer using str() :

std::ostringstream buf;

std::copy(directory_iterator(p), directory_iterator(),
          std::ostream_iterator<directory_entry>(buf, "\n"));

std::string content(buf.str());

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