std::basic_ifstream::swap(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸŽ€ NAME πŸŽ€

std::basic_ifstream::swap β€” std::basic_ifstream::swap, bestie. That’s the whole name, and honestly? Iconic minimalism. This page comes straight from the C++ Standard Libary manual, and it’s giving β€œniche but essential” πŸ’…


✨ Synopsis ✨

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

Exchanges the state of the stream with those of other. Fr fr, the vibes get swapped.

This is done by calling basic_istream<CharT, Traits>::swap(other) and rdbuf()->swap(other.rdbuf()). The way that’s so specific and still lowkey tidy 🫢


🫢 Parameters 🫢

  • other β€” the stream you’re exchanging state with, bestie.

🌈 Return value 🌈

Literally (none). No return value, no drama, no crumbs 😌


😭 Exceptions 😭

May throw implementation-defined exceptions. So like… the implementation is the main character here, and it gets to decide what chaos it throws πŸ’€


🧚 Example 🧚

        // Run this code

        #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); // stream objects are not copyable
                    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);
            }
        }

πŸ“ Possible output πŸ“

data: "/tmp/test_file.txt"

πŸ‘‘ See also πŸ‘‘

  • operator= β€” moves the file stream (C++11) (public member function)
  • swap β€” swaps two basic_filebuf objects (C++11) (public member function of std::basic_filebuf<CharT,Traits>)

source: http://cppreference.com Β· version/date: 2024.06.10 Β· page: std::basic_ifstream::swap(3) β€” mwah, stay hydrated and keep those streams swappable πŸ’‹βœ¨

πŸ“¦ where this page comes from