std::basic_...am::is_open(3)

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

✨ NAME ✨

std::basic_ifstream::is_open β€” bestie, it's literally std::basic_ifstream::is_open πŸ’…

(this is a page from the C++ Standard Library manual, btw β€” keeping you informed 🫢)


🌸 SYNOPSIS 🌸

okay so here's the whole vibe, no cap:

bool is_open() const;

What it does? Checks if the file stream has an associated file. That's it. That's the function. πŸŽ€

Under the hood it's effectively calling rdbuf()->is_open(), so like, it's not doing anything magical β€” it's just asking its buddy rdbuf() to do the actual checking. iykyk ✨


πŸ¦‹ PARAMETERS πŸ¦‹

  • (none) β€” bestie takes zero arguments, she needs NOTHING from you πŸ’€

⭐ RETURN VALUE ⭐

  • true β€” if the file stream has an associated file πŸŽ‰
  • false β€” otherwise 😭

that's the whole thing. very demure. very mindful. 🌈


πŸ”₯ EXAMPLE πŸ”₯

// Run this code

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

// this file is called main.cpp

bool file_exists(const std::string& str)
{
    std::ifstream fs(str);
    return fs.is_open();
}

int main()
{
    std::boolalpha(std::cout);
    std::cout << file_exists("main.cpp")  << '\n'
              << file_exists("strange_file") << '\n';
}

okay so notice std::boolalpha(std::cout) β€” that's the main character move that makes it print true/false instead of 1/0. obsessed. πŸ‘‘

🌸 Possible output 🌸

true
false

like, main.cpp exists (obviously, it's right there), and strange_file... does not. the audacity honestly πŸ™ˆ


πŸ’œ DEFECT REPORTS πŸ’œ

so there were these behavior-changing defect reports that got applied retroactively to previously published C++ standards β€” which is lowkey wild when you think about it, they went back and fixed the past πŸ’€

Here's the tea:

  • DR: LWG 365
  • Applied to: C++98
  • Behavior as published: is_open was not declared with const qualifier
  • Correct behavior: declared with const qualifier

so yeah, it got that const glow-up and honestly she deserved it πŸŽ€βœ¨


🧚 SEE ALSO 🧚

  • open β€” opens a file and associates it with the stream (public member function) πŸ¦‹
  • close β€” closes the associated file (public member function) πŸ’…

and that's the page bestie!! go check your streams, stay hydrated, and remember: if is_open() returns false, it's not you, it's the file path πŸ˜­πŸ’–

πŸ’– courtesy of http://cppreference.com β€” version 2024.06.10 β€” slay safe out there πŸŽ€βœ¨

πŸ“¦ where this page comes from