2 * Copyright 2019 Intel Corporation
3 * SPDX-License-Identifier: MIT
17 #define fdopen _fdopen
18 #define O_CREAT _O_CREAT
19 #define O_EXCL _O_EXCL
20 #define O_WRONLY _O_WRONLY
25 os_file_create_unique(const char *filename
, int filemode
)
27 int fd
= open(filename
, O_CREAT
| O_EXCL
| O_WRONLY
, filemode
);
30 return fdopen(fd
, "w");
34 #if defined(__linux__)
42 readN(int fd
, char *buf
, size_t len
)
47 ssize_t ret
= read(fd
, buf
+ total
, len
- total
);
52 if (ret
== -EINTR
|| ret
== -EAGAIN
)
61 } while (total
!= len
);
63 return total
? (ssize_t
)total
: err
;
67 os_read_file(const char *filename
)
69 /* Note that this also serves as a slight margin to avoid a 2x grow when
70 * the file is just a few bytes larger when we read it than when we
72 * The string's NULL terminator is also included in here.
76 int fd
= open(filename
, O_RDONLY
);
78 /* errno set by open() */
82 /* Pre-allocate a buffer at least the size of the file if we can read
86 if (fstat(fd
, &stat
) == 0)
89 char *buf
= malloc(len
);
96 ssize_t actually_read
;
97 size_t offset
= 0, remaining
= len
- 1;
98 while ((actually_read
= readN(fd
, buf
+ offset
, remaining
)) == (ssize_t
)remaining
) {
99 char *newbuf
= realloc(buf
, 2 * len
);
109 offset
+= actually_read
;
110 remaining
= len
- offset
- 1;
115 if (actually_read
> 0)
116 offset
+= actually_read
;
118 /* Final resize to actual size */
120 char *newbuf
= realloc(buf
, len
);
136 os_read_file(const char *filename
)