| 32 | |
| 33 | #ifndef TFLITE_MCU |
| 34 | FileCopyAllocation::FileCopyAllocation(const char* filename, |
| 35 | ErrorReporter* error_reporter) |
| 36 | : Allocation(error_reporter, Allocation::Type::kFileCopy) { |
| 37 | // Obtain the file size, using an alternative method that is does not |
| 38 | // require fstat for more compatibility. |
| 39 | std::unique_ptr<FILE, decltype(&fclose)> file(fopen(filename, "rb"), fclose); |
| 40 | if (!file) { |
| 41 | error_reporter_->Report("Could not open '%s'.", filename); |
| 42 | return; |
| 43 | } |
| 44 | // TODO(ahentz): Why did you think using fseek here was better for finding |
| 45 | // the size? |
| 46 | struct stat sb; |
| 47 | |
| 48 | // support usage of msvc's posix-like fileno symbol |
| 49 | #ifdef _WIN32 |
| 50 | #define FILENO(_x) _fileno(_x) |
| 51 | #else |
| 52 | #define FILENO(_x) fileno(_x) |
| 53 | #endif |
| 54 | if (fstat(FILENO(file.get()), &sb) != 0) { |
| 55 | error_reporter_->Report("Failed to get file size of '%s'.", filename); |
| 56 | return; |
| 57 | } |
| 58 | #undef FILENO |
| 59 | buffer_size_bytes_ = sb.st_size; |
| 60 | std::unique_ptr<char[]> buffer(new char[buffer_size_bytes_]); |
| 61 | if (!buffer) { |
| 62 | error_reporter_->Report("Malloc of buffer to hold copy of '%s' failed.", |
| 63 | filename); |
| 64 | return; |
| 65 | } |
| 66 | size_t bytes_read = |
| 67 | fread(buffer.get(), sizeof(char), buffer_size_bytes_, file.get()); |
| 68 | if (bytes_read != buffer_size_bytes_) { |
| 69 | error_reporter_->Report("Read of '%s' failed (too few bytes read).", |
| 70 | filename); |
| 71 | return; |
| 72 | } |
| 73 | // Versions of GCC before 6.2.0 don't support std::move from non-const |
| 74 | // char[] to const char[] unique_ptrs. |
| 75 | copied_buffer_.reset(const_cast<char const*>(buffer.release())); |
| 76 | } |
| 77 | |
| 78 | FileCopyAllocation::~FileCopyAllocation() {} |
| 79 | |