scoped_file.h 2.0 KB

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