std::fclose(3)

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

πŸ’– NAME πŸ’–

okay so bestie, welcome to the std::fclose(3) page from the C++ Standard Libary β€” and the NAME section is literally:

std::fclose β€” std::fclose

yes, that’s the whole thing. short, iconic, main character energy. πŸ’…


✨ Synopsis ✨

It’s defined in header <cstdio>, and the signature is:

Defined in header <cstdio>
int fclose( std::FILE* stream );

So the way this works: it closes the given file stream. Any unwritten buffered data are flushed to the OS, and any unread buffered data are discarded β€” like, bye to the unread stuff, fr. πŸ‘‹

Whether or not the operation succeeds, the stream is no longer associated with a file, and the buffer allocated by std::setbuf or std::setvbuf, if any, is also disassociated and deallocated if automatic allocation was used. no cap, that happens either way. πŸ’–

⚠️ The behavior is undefined if the value of the pointer stream is used after fclose returns. translation: after close, do not touch stream β€” that’s undefined behavior, and undefined behavior is not cute. πŸ’€

🌸 Parameters 🌸

  • stream β€” the file stream to close. that’s the whole parameter list, bestie. 🫢

πŸŽ€ Return value πŸŽ€

  • 0 on success, EOF otherwise. slay. ✨

πŸ¦‹ Example πŸ¦‹

The page says // Run this code, so bestie, run it β€” full example, preserved exactly:

        #include <cstdio>
        #include <cstdlib>

        int main()
        {
            int is_ok = EXIT_FAILURE;
            FILE* fp = std::fopen("/tmp/test.txt", "w+");
            if (!fp)
            {
                std::perror("File opening failed");
                return is_ok;
            }

            int c; // Note: int, not char, required to handle EOF
            while ((c = std::fgetc(fp)) != EOF) // Standard C I/O file reading
       loop
                std::putchar(c);

            if (std::ferror(fp))
                std::puts("I/O error when reading");
            else if (std::feof(fp))
            {
                std::puts("End of file reached successfully");
                is_ok = EXIT_SUCCESS;
            }

            std::fclose(fp);
            return is_ok;
        }

Output, when it runs:

End of file reached successfully

🌈 See also 🌈

  • fopen β€” opens a file (function). πŸ”₯
  • freopen β€” open an existing stream with a different name (function). 🌟
  • close β€” flushes the put area buffer and closes the associated file (public member function of std::basic_filebuf<CharT,Traits>). πŸ‘‘
  • C documentation for fclose. πŸ’œ

xoxo, your Unix bestie πŸ’… β€” this page comes from the C++ Standard Libary, source/version: http://cppreference.com, date: 2024.06.10, and the manual page is std::fclose(3). bye bestie, close those streams responsibly! πŸŽ€πŸ¦‹

πŸ“¦ where this page comes from