File: OpenFileHandle.h

package info (click to toggle)
cryfs 1.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 28,412 kB
  • sloc: cpp: 150,187; asm: 10,493; python: 1,455; javascript: 65; sh: 50; makefile: 17; xml: 7
file content (49 lines) | stat: -rw-r--r-- 1,086 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#pragma once
#ifndef MESSMER_FSPP_TEST_TESTUTILS_OPENFILEHANDLE_H_
#define MESSMER_FSPP_TEST_TESTUTILS_OPENFILEHANDLE_H_

#include <fcntl.h>
#include <cpp-utils/macros.h>
#include <errno.h>
#include <thread>
#include <chrono>
#if defined(_MSC_VER)
#include <io.h>
#else
#include <unistd.h>
#endif

class OpenFileHandle final {
public:
    OpenFileHandle(const char *path, int flags): fd_(::open(path, flags)), errno_(fd_ >= 0 ? 0 : errno) {
    }

    OpenFileHandle(const char *path, int flags, int flags2): fd_(::open(path, flags, flags2)), errno_(fd_ >= 0 ? 0 : errno) {
    }

    ~OpenFileHandle() {
        if (fd_ >= 0) {
            ::close(fd_);
#ifdef __APPLE__
            // On Mac OS X, we might have to give it some time to free up the file
            std::this_thread::sleep_for(std::chrono::milliseconds(50));
#endif
        }
    }

    int fd() { return fd_; }
    int errorcode() { return errno_; }

    void release() {
        fd_ = -1; // don't close anymore
    }

private:
    int fd_;
    int errno_;

    DISALLOW_COPY_AND_ASSIGN(OpenFileHandle);
};


#endif