Kea  2.3.5-git
file_utilities.cc
Go to the documentation of this file.
1 // Copyright (C) 2021-2022 Internet Systems Consortium, Inc. ("ISC")
2 //
3 // This Source Code Form is subject to the terms of the Mozilla Public
4 // License, v. 2.0. If a copy of the MPL was not distributed with this
5 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
6 
7 #include <config.h>
8 
10 #include <util/filename.h>
11 #include <cerrno>
12 #include <cstring>
13 #include <fcntl.h>
14 #include <sys/stat.h>
15 
16 using namespace std;
17 
18 namespace isc {
19 namespace util {
20 namespace file {
21 
22 string
23 getContent(const string& file_name) {
24  // Open the file.
25  int fd = ::open(file_name.c_str(), O_RDONLY);
26  if (fd < 0) {
27  isc_throw(BadValue, "can't open file '" << file_name << "': "
28  << std::strerror(errno));
29  }
30  try {
31  struct stat stats;
32  if (fstat(fd, &stats) < 0) {
33  isc_throw(BadValue, "can't stat file '" << file_name << "': "
34  << std::strerror(errno));
35  }
36  if ((stats.st_mode & S_IFMT) != S_IFREG) {
37  isc_throw(BadValue, "'" << file_name
38  << "' must be a regular file");
39  }
40  string content(stats.st_size, ' ');
41  ssize_t got = ::read(fd, &content[0], stats.st_size);
42  if (got < 0) {
43  isc_throw(BadValue, "can't read file '" << file_name << "': "
44  << std::strerror(errno));
45  }
46  if (got != stats.st_size) {
47  isc_throw(BadValue, "can't read whole file '" << file_name
48  << "' (got " << got << " of " << stats.st_size << ")");
49  }
50  static_cast<void>(close(fd));
51  return (content);
52  } catch (const std::exception&) {
53  static_cast<void>(close(fd));
54  throw;
55  }
56 }
57 
58 bool
59 isDir(const string& name) {
60  struct stat stats;
61  if (::stat(name.c_str(), &stats) < 0) {
62  return (false);
63  }
64  return ((stats.st_mode & S_IFMT) == S_IFDIR);
65 }
66 
67 } // namespace file
68 } // namespace log
69 } // namespace isc
STL namespace.
#define isc_throw(type, stream)
A shortcut macro to insert known values into exception arguments.
A generic exception that is thrown if a parameter given to a method is considered invalid in that con...
string getContent(const string &file_name)
Get the content of a regular file.
bool isDir(const string &name)
Is a directory predicate.
Defines the logger used by the top-level component of kea-lfc.