Skip to content

Commit

Permalink
Add file reading
Browse files Browse the repository at this point in the history
  • Loading branch information
jkurdek committed Aug 23, 2024
1 parent c8b530f commit 3abb6e0
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 4 deletions.
1 change: 1 addition & 0 deletions samples/large_sample_compact.json

Large diffs are not rendered by default.

64 changes: 60 additions & 4 deletions src/main.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,62 @@
#include <rapidjson/document.h>

#include <cstdlib>
#include <exception>
#include <fstream>
#include <iostream>
#include <span>
#include <stdexcept>
#include <string>

constexpr double GIGABYTE = 1e9;

/**
* Reads the contents of a file into a dynamically allocated buffer.
*
* @param filename The name of the file to be read.
* @return A string containing the contents of the file.
*/
std::string readFile(const std::string& filename) {
std::ifstream file(filename, std::ios::binary | std::ios::ate);

if (!file) {
throw std::runtime_error("Error opening file: " + filename);
}

auto fileSize = file.tellg();
file.seekg(0, std::ios::beg);

std::string buffer(fileSize, '\0');

if (!file.read(buffer.data(), fileSize)) {
throw std::runtime_error("Error reading file: " + filename);
}

return buffer;
}

int main(int argc, char* argv[]) {
try {
auto args = std::span(argv, argc);

if (argc < 2) {
std::cerr << "Usage: " << args[0] << " <filename>" << "\n";
return 1;
}

const std::string filename = args[1];

std::cout << "Reading file: " << filename << "\n";
auto buffer = readFile(filename);
std::cout << "Done reading! File size: " << static_cast<double>(buffer.size()) / GIGABYTE << " GB" << "\n";

if (buffer.empty()) {
return 1;
}

int main() { return EXIT_SUCCESS; }
} catch (const std::exception& e) {
std::cerr << "Exception caught: " << e.what() << "\n";
return 1;
} catch (...) {
std::cerr << "Unknown exception caught" << "\n";
return 1;
}
return 0;
}

0 comments on commit 3abb6e0

Please sign in to comment.