1 // Copyright 2015 The Chromium OS 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 
5 #include "file_reader.h"
6 
7 #include <string.h>
8 
9 #include <memory>
10 
11 namespace quipper {
12 
13 FileReader::FileReader(const string& filename) {
14   infile_ = fopen(filename.c_str(), "rb");
15   if (!IsOpen()) {
16     size_ = 0;
17     return;
18   }
19   // Determine the size of the file.
20   fseek(infile_, 0, SEEK_END);
21   size_ = ftell(infile_);
22 
23   // Reset to the beginning of the file.
24   fseek(infile_, 0, SEEK_SET);
25 }
26 
27 FileReader::~FileReader() {
28   if (IsOpen()) {
29     fclose(infile_);
30   }
31 }
32 
33 bool FileReader::ReadData(const size_t size, void* dest) {
34   if (Tell() + size > size_ || fread(dest, 1, size, infile_) < size)
35     return false;
36   return true;
37 }
38 
39 bool FileReader::ReadString(const size_t size, string* str) {
40   if (!ReadDataString(size, str)) return false;
41 
42   // Truncate anything after a terminating null.
43   size_t actual_length = strnlen(str->data(), size);
44   str->resize(actual_length);
45   return true;
46 }
47 
48 }  // namespace quipper
49