BDE 4.14.0 Production release
|
Provide a RAII guard class used to close files.
This component defines a class, bdls::FileDescriptorGuard
, an object of which manages an open file descriptor, and closes it when the guard goes out of scope and is destroyed. A release
method is provided, which will release the descriptor from management by the guard. When a released guard is destroyed, nothing happens. A closeAndRelease
method is also provided, which closes the managed file handle and puts the guard into a released state.
This section illustrates intended use of this component.
Suppose we want to open a file and perform some I/O operations. We use an object of type bdls::FileDescriptorGuard
to ensure this handle is closed after the operations are complete.
First, we create a name for our temporary file name and a few local variables.
Then, we open the file:
Next, we enter a lexical scope and create a guard object to manage fd
:
Then, we declare an essay we would like to write to the file:
Next, we write our essay to the file:
Now, guard
goes out of scope, and its destructor closes the file descriptor.
Finally, we observe that further attempts to access fd
fail because the descriptor has been closed: