diff options
Diffstat (limited to 'src/utility.h')
-rw-r--r-- | src/utility.h | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/src/utility.h b/src/utility.h new file mode 100644 index 0000000..7050cee --- /dev/null +++ b/src/utility.h @@ -0,0 +1,48 @@ +#include <sys/stat.h> +#include <fcntl.h> +#include <unistd.h> + +#include <cstddef> +#include <cstdio> + +namespace { + +const int OpenFlags = O_RDONLY; +const mode_t OpenMode = S_IRUSR | S_IWUSR; + +} + +std::string readFile(const std::string& path) { + int descriptor( + open(path.data(), OpenFlags, OpenMode) + ); + + if ( descriptor == -1 ) { + close(descriptor); + + return "io error"; + } else { + struct stat info; + fstat(descriptor, &info); + const std::size_t size(info.st_size); + + char* buffer(new char[size]); + + ssize_t readSize(read( + descriptor, + reinterpret_cast<void*>(buffer), + size + )); + + close(descriptor); + + std::string content( + buffer, + readSize + ); + + delete[] buffer; + + return content; + } +} |