Flutter Engine
 
Loading...
Searching...
No Matches
file.cc
Go to the documentation of this file.
1// Copyright 2013 The Flutter 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
6
7#include <fcntl.h>
8#include <stdlib.h>
9#include <sys/stat.h>
10
11#include <climits>
12#include <cstdint>
13
15
16#if defined(OS_WIN)
17#define BINARY_MODE _O_BINARY
18#else
19#define BINARY_MODE 0
20#endif
21
22#if defined(OS_WIN)
23#include <BaseTsd.h>
24typedef SSIZE_T ssize_t;
25#endif
26
29
30namespace filesystem {
31namespace {
32
33template <typename T>
34bool ReadFileDescriptor(int fd, T* result) {
35 if (!result) {
36 return false;
37 }
38
39 result->clear();
40
41 if (fd < 0)
42 return false;
43
44 constexpr size_t kBufferSize = 1 << 16;
45 size_t offset = 0;
46 ssize_t bytes_read = 0;
47 do {
48 offset += bytes_read;
49 result->resize(offset + kBufferSize);
50 bytes_read = HANDLE_EINTR(read(fd, &(*result)[offset], kBufferSize));
51 } while (bytes_read > 0);
52
53 if (bytes_read < 0) {
54 result->clear();
55 return false;
56 }
57
58 result->resize(offset + bytes_read);
59 return true;
60}
61
62} // namespace
63
64std::pair<uint8_t*, intptr_t> ReadFileDescriptorToBytes(int fd) {
65 std::pair<uint8_t*, intptr_t> failure_pair{nullptr, -1};
66 struct stat st;
67 if (fstat(fd, &st) != 0) {
68 return failure_pair;
69 }
70 intptr_t file_size = st.st_size;
71 uint8_t* ptr = (uint8_t*)malloc(file_size);
72
73 size_t bytes_left = file_size;
74 size_t offset = 0;
75 while (bytes_left > 0) {
76 ssize_t bytes_read = HANDLE_EINTR(read(fd, &ptr[offset], bytes_left));
77 if (bytes_read < 0) {
78 return failure_pair;
79 }
80 offset += bytes_read;
81 bytes_left -= bytes_read;
82 }
83 return std::pair<uint8_t*, intptr_t>(ptr, file_size);
84}
85
86bool ReadFileToString(const std::string& path, std::string* result) {
87 Descriptor fd(open(path.c_str(), O_RDONLY));
88 return ReadFileDescriptor(fd.get(), result);
89}
90
91bool ReadFileDescriptorToString(int fd, std::string* result) {
92 return ReadFileDescriptor(fd, result);
93}
94
95std::pair<uint8_t*, intptr_t> ReadFileToBytes(const std::string& path) {
96 std::pair<uint8_t*, intptr_t> failure_pair{nullptr, -1};
97 Descriptor fd(open(path.c_str(), O_RDONLY | BINARY_MODE));
98 if (!fd.is_valid())
99 return failure_pair;
100 return ReadFileDescriptorToBytes(fd.get());
101}
102
103} // namespace filesystem
bool ReadFileDescriptorToString(int fd, std::string *result)
Definition file.cc:91
bool ReadFileToString(const std::string &path, std::string *result)
Definition file.cc:86
std::pair< uint8_t *, intptr_t > ReadFileToBytes(const std::string &path)
Definition file.cc:95
std::pair< uint8_t *, intptr_t > ReadFileDescriptorToBytes(int fd)
Definition file.cc:64
#define HANDLE_EINTR(x)
#define BINARY_MODE
Definition file.cc:19
LONG_PTR SSIZE_T