scoped_file.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright 2014 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_FILES_SCOPED_FILE_H_
  5. #define BASE_FILES_SCOPED_FILE_H_
  6. #include <stdio.h>
  7. #include <memory>
  8. #include "base/base_export.h"
  9. #include "base/logging.h"
  10. #include "base/scoped_generic.h"
  11. #include "build/build_config.h"
  12. namespace base {
  13. namespace internal {
  14. #if defined(OS_ANDROID)
  15. // Use fdsan on android.
  16. struct BASE_EXPORT ScopedFDCloseTraits : public ScopedGenericOwnershipTracking {
  17. static int InvalidValue() { return -1; }
  18. static void Free(int);
  19. static void Acquire(const ScopedGeneric<int, ScopedFDCloseTraits>&, int);
  20. static void Release(const ScopedGeneric<int, ScopedFDCloseTraits>&, int);
  21. };
  22. #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
  23. struct BASE_EXPORT ScopedFDCloseTraits {
  24. static int InvalidValue() {
  25. return -1;
  26. }
  27. static void Free(int fd);
  28. };
  29. #endif
  30. // Functor for |ScopedFILE| (below).
  31. struct ScopedFILECloser {
  32. inline void operator()(FILE* x) const {
  33. if (x)
  34. fclose(x);
  35. }
  36. };
  37. } // namespace internal
  38. // -----------------------------------------------------------------------------
  39. #if defined(OS_POSIX) || defined(OS_FUCHSIA)
  40. // A low-level Posix file descriptor closer class. Use this when writing
  41. // platform-specific code, especially that does non-file-like things with the
  42. // FD (like sockets).
  43. //
  44. // If you're writing low-level Windows code, see base/win/scoped_handle.h
  45. // which provides some additional functionality.
  46. //
  47. // If you're writing cross-platform code that deals with actual files, you
  48. // should generally use base::File instead which can be constructed with a
  49. // handle, and in addition to handling ownership, has convenient cross-platform
  50. // file manipulation functions on it.
  51. typedef ScopedGeneric<int, internal::ScopedFDCloseTraits> ScopedFD;
  52. #endif
  53. // Automatically closes |FILE*|s.
  54. typedef std::unique_ptr<FILE, internal::ScopedFILECloser> ScopedFILE;
  55. } // namespace base
  56. #endif // BASE_FILES_SCOPED_FILE_H_