Quick Links:

bal | bbl | bdl | bsl

Namespaces

Component bdls_filedescriptorguard
[Package bdls]

Provide a RAII guard class used to close files. More...

Namespaces

namespace  bdls

Detailed Description

Outline
Purpose:
Provide a RAII guard class used to close files.
Classes:
bdls::FileDescriptorGuard RAII guard class used to close files
See also:
Component bdls_filesystemutil
Description:
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.
Usage:
Example 1: Close a File Descriptor:
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.
  const bsl::string fileName = "essay.txt";
  int rc;
Then, we open the file:
  Util::FileDescriptor fd = Util::open(fileName,
                                       Util::e_CREATE,
                                       Util::e_READ_WRITE);
  assert(Util::k_INVALID_FD != fd);
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:
      const char essay[] = {
                         "If you can't annoy somebody, there is little\n"
                         "point in writing.\n"
                         "                Kingsley Amis\n"
                         "\n"
                         "It takes a lifetime to build a reputation, and\n"
                         "five minutes to lose it.\n"
                         "                Warren Buffet\n"
                         "\n"
                         "Originality is stubborn but not indestructible.\n"
                         "You can't tell it what to do, and if you try too\n"
                         "hard to steer it, you either chase it away or\n"
                         "murder it.\n"
                         "                Salman Khan\n" };
Next, we write our essay to the file:
      rc = Util::write(fd, essay, sizeof(essay));
      assert(sizeof(essay) == rc);
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:
  Util::Offset off = Util::seek(fd,
                                0,
                                Util::e_SEEK_FROM_BEGINNING);
  assert(-1 == off);