# std::basic_filebuf<CharT,Traits>::close

> C++ Atlas: `cppatlas.com/w/cpp/io/basic_filebuf/close` | Source: https://en.cppreference.com/w/cpp/io/basic_filebuf/close | Domain: Input/output

If a put area exist (e.g. file was opened for writing), first calls overflow(Traits::eof()) to write all pending output to the file, including any unshift sequences.

## Official Specification Summary (cppreference)

```cpp
std::basic_filebuf<CharT, Traits>* close();
```

If a put area exist (e.g. file was opened for writing), first calls `overflow(Traits::eof())` to write all pending output to the file, including any unshift sequences.

If the most recently called function, out of `underflow()`, `overflow()`, `seekpos()`, and `seekoff()`, was `overflow()`, then calls `std::codecvt::unshift()`, perhaps multiple times, to determine the unshift sequence according to the imbued locale, and writes that sequence to file with `overflow(Traits::eof())`.

Then, closes the file as if by calling `std::fclose()`, regardless of whether any of the preceding calls succeeded or failed.

If any of the function calls made, including the call to `std::fclose()`, fails, returns a null pointer. If any of the function calls made throws an exception, the exception is caught and rethrown after closing the file. If the file is already closed, returns a null pointer right away.

In any case, updates the private member variable that is accessed by `is_open()`.

### Parameters

(none)

### Return value

`this` on success, a null pointer on failure.

### Notes

`close()` is typically called through the destructor of `std::basic_filebuf` (which, in turn, is typically called by the destructor of `std::basic_fstream`.

### Example

> Note: This section is incomplete Reason: no example

### Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| LWG 443 | C++98 | the file was written using `overflow(EOF)` | changed to `overflow(Traits::eof())` |
| LWG 622 | C++98 | it was unclear how to handle the exception thrown during closing | it is rethrown after closing the file |

### See also

- [`is_open`](https://en.cppreference.com/w/cpp/io/basic_filebuf/is_open): checks if the associated file is open (public member function)
- [(destructor)](https://en.cppreference.com/w/cpp/io/basic_filebuf/~basic_filebuf) [virtual]: destructs a `basic_filebuf` object and closes the file if it is open (virtual public member function)

---
Attribution: content from https://en.cppreference.com/w/cpp/io/basic_filebuf/close (cppreference.com), licensed under CC-BY-SA 3.0 and GFDL. Modified: converted to markdown, study notes added. Offline snapshot of 9 February 2025.