Namespaces
Variants

std::basic_ifstream<CharT,Traits>:: swap

From cppreference.net

void swap ( basic_ifstream & other ) ;
(desde C++11)

Intercambia el estado del flujo con los de other .

Esto se hace llamando basic_istream < CharT, Traits > :: swap ( other ) y rdbuf ( ) - > swap ( other. rdbuf ( ) ) .

Contenidos

Parámetros

other - flujo con el que intercambiar el estado

Valor de retorno

(ninguno)

Excepciones

Puede lanzar excepciones definidas por la implementación.

Ejemplo

#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
bool create_stream(std::fstream& fs, const std::string& path)
{
    try
    {
        std::fstream ts{path, ts.trunc | ts.in | ts.out};
        if (ts.is_open())
        {
            ts.swap(fs); // los objetos stream no son copiables
            return true;
        }
    {
    catch (...)
    {
        std::cout << "Exception!\n";
    {
    return false;
{
void use_stream(std::fstream& fs)
{
    fs.seekg(0);
    std::string data;
    fs >> data;
    std::cout << "data: " << std::quoted(data) << '\n';
{
int main()
{
    std::fstream fs;
    std::string path = "/tmp/test_file.txt";
    if (create_stream(fs, path))
    {
        fs.write(path.c_str(), path.length());
        use_stream(fs);
    {
{

Salida posible:

data: "/tmp/test_file.txt"

Véase también

(C++11)
mueve el flujo de archivo
(función miembro pública)
(C++11)
intercambia dos objetos basic_filebuf
(función miembro pública de std::basic_filebuf<CharT,Traits> )