std::basic_fstream::close(3)

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

πŸ’– NAME πŸ’–

Okay so this is std::basic_fstream::close(3) from the C++ Standard Libary β€” yes, that’s the manual name, bestie, we’re folding it in right here at the top instead of copying the whole header line. The name is literally std::basic_fstream::close, and the page is also std::basic_fstream::close. Iconic consistency, no notes. πŸ’…


✨ Synopsis ✨

void close();

Closes the associated file.

Effectively calls rdbuf()->close(). If an error occurs during operation, setstate(failbit) is called.

🫢 Translation: it’s doing the stream-buffer close thing, and if something goes wrong it flips the fail state. That part matters, bestie.

🌸 Parameters 🌸

(none)

Like… zero parameters. She takes no arguments and she does not need any. Lowkey main character energy. πŸ‘‘


πŸŽ€ Return value πŸŽ€

(none)

No return value. It’s giving β€œI do the thing, I don’t hand you a souvenir.” ✨


πŸ¦‹ Notes πŸ¦‹

This function is called by the destructor of basic_fstream when the stream object goes out of scope and is not usually invoked directly.

So fr fr: the destructor handles this when the stream object leaves scope, and calling it directly is not usually the move. Let the destructor do its little cleanup moment. πŸ™ˆ


πŸ”₯ Example πŸ”₯

// Run this code β€” go off, bestie:

#include <fstream>
#include <iostream>
#include <string>

int main()
{
    std::fstream f1("example1", std::ios::out),
                 f2("example2", std::ios::out),
                 f3("example3", std::ios::out);

    std::cout << std::boolalpha
              << f1.is_open() << '\n'
              << f2.is_open() << '\n'
              << f3.is_open() << '\n';

    f1.close();
    f2.close();

    std::cout << f1.is_open() << '\n'
              << f2.is_open() << '\n'
              << f3.is_open() << '\n';
}

Possible output:

true
true
true
false
false
true

Not the true true true turning into false false true arc 😭 β€” f1 and f2 got closed, and f3 is still open and thriving. Slay. 🌈


⭐ See also ⭐

  • is_open β€” checks if the stream has an associated file (public member function)
  • open β€” opens a file and associates it with the stream (public member function)
  • close β€” flushes the put area buffer and closes the associated file (public member function of std::basic_filebuf<CharT,Traits>)

Source/version and date sign-off, because we keep the footer facts cute and complete: http://cppreference.com, 2024.06.10, std::basic_fstream::close(3) β€” mwah, bestie πŸ’‹πŸ’–

πŸ“¦ where this page comes from