OR-Tools  9.6
file_util.h
Go to the documentation of this file.
1 // Copyright 2010-2022 Google LLC
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 #ifndef OR_TOOLS_UTIL_FILE_UTIL_H_
15 #define OR_TOOLS_UTIL_FILE_UTIL_H_
16 
17 #include <limits>
18 #include <string>
19 #include <vector>
20 
21 #include "absl/status/statusor.h"
22 #include "absl/strings/string_view.h"
23 #include "google/protobuf/message.h"
24 #include "ortools/base/file.h"
25 #include "ortools/base/helpers.h"
26 #include "ortools/base/recordio.h"
27 
28 namespace operations_research {
29 
30 // Reads a file, optionally gzipped, to a string.
31 absl::StatusOr<std::string> ReadFileToString(absl::string_view filename);
32 
33 // Reads a proto from a file. Supports the following formats: binary, text,
34 // JSON, all of those optionally gzipped. Crashes on filesystem failures, e.g.
35 // file unreadable. Returns false on format failures, e.g. the file could be
36 // read, but the contents couldn't be parsed -- or maybe it was a valid JSON,
37 // text proto, or binary proto, but not of the right proto message.
38 // Returns true on success.
39 bool ReadFileToProto(absl::string_view filename,
40  google::protobuf::Message* proto);
41 
42 template <typename Proto>
43 Proto ReadFileToProtoOrDie(absl::string_view filename) {
44  Proto proto;
45  CHECK(ReadFileToProto(filename, &proto)) << "with file: '" << filename << "'";
46  return proto;
47 }
48 
49 // Specifies how the proto should be formatted when writing it to a file.
50 // kCanonicalJson converts field names to lower camel-case.
52 
53 // Writes a proto to a file. Supports the following formats: binary, text, JSON,
54 // all of those optionally gzipped. Returns false on failure.
55 // If 'proto_write_format' is kProtoBinary, ".bin" is appended to file_name. If
56 // 'proto_write_format' is kJson or kCanonicalJson, ".json" is appended to
57 // file_name. If 'gzipped' is true, ".gz" is appended to file_name.
58 bool WriteProtoToFile(absl::string_view filename,
59  const google::protobuf::Message& proto,
60  ProtoWriteFormat proto_write_format, bool gzipped = false,
61  bool append_extension_to_file_name = true);
62 
63 namespace internal {
64 // General method to read expected_num_records from a file. If
65 // expected_num_records is -1, then reads all records from the file. If not,
66 // dies if the file doesn't contain exactly expected_num_records.
67 template <typename Proto>
68 std::vector<Proto> ReadNumRecords(File* file, int expected_num_records) {
70  std::vector<Proto> protos;
71  Proto proto;
72  int num_read = 0;
73  while (num_read != expected_num_records &&
74  reader.ReadProtocolMessage(&proto)) {
75  protos.push_back(proto);
76  ++num_read;
77  }
78 
79  CHECK(reader.Close())
80  << "File '" << file->filename()
81  << "'was not fully read, or something went wrong when closing "
82  "it. Is it the right format? (RecordIO of Protocol Buffers).";
83 
84  if (expected_num_records >= 0) {
85  CHECK_EQ(num_read, expected_num_records)
86  << "There were less than the expected " << expected_num_records
87  << " in the file.";
88  }
89 
90  return protos;
91 }
92 
93 // Ditto, taking a filename as argument.
94 template <typename Proto>
95 std::vector<Proto> ReadNumRecords(absl::string_view filename,
96  int expected_num_records) {
97  return ReadNumRecords<Proto>(file::OpenOrDie(filename, "r", file::Defaults()),
98  expected_num_records);
99 }
100 } // namespace internal
101 
102 // Reads all records in Proto format in 'file'. Silently does nothing if the
103 // file is empty. Dies if the file doesn't exist or contains something else than
104 // protos encoded in RecordIO format.
105 template <typename Proto>
106 std::vector<Proto> ReadAllRecordsOrDie(absl::string_view filename) {
107  return internal::ReadNumRecords<Proto>(filename, -1);
108 }
109 template <typename Proto>
110 std::vector<Proto> ReadAllRecordsOrDie(File* file) {
111  return internal::ReadNumRecords<Proto>(file, -1);
112 }
113 
114 // Reads one record from file, which must be in RecordIO binary proto format.
115 // Dies if the file can't be read, doesn't contain exactly one record, or
116 // contains something else than the expected proto in RecordIO format.
117 template <typename Proto>
118 Proto ReadOneRecordOrDie(absl::string_view filename) {
119  Proto p;
120  p.Swap(&internal::ReadNumRecords<Proto>(filename, 1)[0]);
121  return p;
122 }
123 
124 // Writes all records in Proto format to 'file'. Dies if it is unable to open
125 // the file or write to it.
126 template <typename Proto>
127 void WriteRecordsOrDie(absl::string_view filename,
128  const std::vector<Proto>& protos) {
129  recordio::RecordWriter writer(
130  file::OpenOrDie(filename, "w", file::Defaults()));
131  for (const Proto& proto : protos) {
132  CHECK(writer.WriteProtocolMessage(proto));
133  }
134  CHECK(writer.Close());
135 }
136 
137 } // namespace operations_research
138 
139 #endif // OR_TOOLS_UTIL_FILE_UTIL_H_
Definition: base/file.h:33
bool ReadProtocolMessage(P *const proto)
Definition: recordio.h:91
bool WriteProtocolMessage(const P &proto)
Definition: recordio.h:41
CpModelProto proto
File * OpenOrDie(const absl::string_view &filename, const absl::string_view &mode, int flags)
Definition: base/file.cc:155
Options Defaults()
Definition: base/file.h:123
std::vector< Proto > ReadNumRecords(File *file, int expected_num_records)
Definition: file_util.h:68
Collection of objects used to extend the Constraint Solver library.
std::vector< Proto > ReadAllRecordsOrDie(absl::string_view filename)
Definition: file_util.h:106
Proto ReadFileToProtoOrDie(absl::string_view filename)
Definition: file_util.h:43
absl::StatusOr< std::string > ReadFileToString(absl::string_view filename)
Definition: file_util.cc:36
bool WriteProtoToFile(absl::string_view filename, const google::protobuf::Message &proto, ProtoWriteFormat proto_write_format, bool gzipped, bool append_extension_to_file_name)
Definition: file_util.cc:112
void WriteRecordsOrDie(absl::string_view filename, const std::vector< Proto > &protos)
Definition: file_util.h:127
bool ReadFileToProto(absl::string_view filename, google::protobuf::Message *proto)
Definition: file_util.cc:47
Proto ReadOneRecordOrDie(absl::string_view filename)
Definition: file_util.h:118