FOSSology  4.4.0
Open Source License Compliance by Open Source Software
files.cc
Go to the documentation of this file.
1 /*
2  SPDX-FileCopyrightText: © 2013-2014 Siemens AG
3 
4  SPDX-License-Identifier: GPL-2.0-only
5 */
6 
7 #include "files.hpp"
8 #include <fstream>
9 #include <sys/stat.h>
10 #include <sstream>
11 
21 namespace fo
22 {
23 
34  std::string getStringFromFile(const char* filename, const unsigned long int maximumBytes)
35  {
36 
37 
38  std::ifstream inStream(filename, std::ios::in | std::ios::binary);
39  if (inStream)
40  {
41  std::string contents;
42  inStream.seekg(0, std::ios::end);
43  if (!(inStream.rdstate() & std::ifstream::failbit))
44  {
45  const unsigned long int endPos = inStream.tellg();
46  contents.resize((maximumBytes > 0 && (endPos > maximumBytes)) ? maximumBytes : endPos);
47  inStream.seekg(0, std::ios::beg);
48  inStream.read(&contents[0], contents.size());
49  }
50  else
51  {
52  // TODO respect limit of maximumBytes
53  inStream.clear(std::ifstream::goodbit);
54 
55  std::stringstream ss;
56  ss << inStream.rdbuf();
57 
58  return ss.str();
59  }
60  inStream.close();
61  return (contents);
62  }
63  throw(errno);
64  }
65 
69  std::string getStringFromFile(std::string const& filename, const unsigned long int maximumBytes)
70  {
71  return getStringFromFile(filename.c_str(), maximumBytes);
72  };
73 
81  std::string File::getContent(const unsigned long int maximumBytes) const
82  {
83  return getStringFromFile(fileName, maximumBytes);
84  }
85 
90  const std::string& File::getFileName() const
91  {
92  return fileName;
93  }
94 
100  File::File(unsigned long _id, const char* _fileName) : id(_id), fileName(_fileName)
101  {
102  }
103 
107  File::File(unsigned long id, std::string const& fileName) : id(id), fileName(fileName)
108  {
109  }
110 
115  unsigned long File::getId() const
116  {
117  return id;
118  }
119 
124  bool File::isReadable() const
125  {
126  struct stat statStr;
127  return (stat(fileName.c_str(), &statStr) == 0);
128  }
129 }
std::string getContent(const unsigned long int maximumBytes=1<< 20) const
Get the content of the file limited by maximumBytes.
Definition: files.cc:81
bool isReadable() const
Definition: files.cc:124
unsigned long getId() const
Definition: files.cc:115
unsigned long id
ID of the file.
Definition: files.hpp:36
std::string fileName
Path of the file.
Definition: files.hpp:37
File(unsigned long id, const char *fileName)
Definition: files.cc:100
const std::string & getFileName() const
Definition: files.cc:90
Utility functions for file handling.
fo namespace holds the FOSSology library functions.
std::string getStringFromFile(const char *filename, const unsigned long int maximumBytes)
Reads the content of a file and return it as a string.
Definition: files.cc:34