NumCpp  2.18.0
A Templatized Header Only C++ Implementation of the Python NumPy Library
Loading...
Searching...
No Matches
fromfile.hpp
Go to the documentation of this file.
1
28#pragma once
29
30#include <filesystem>
31#include <fstream>
32#include <sstream>
33#include <string>
34
36#include "NumCpp/Core/Types.hpp"
38#include "NumCpp/NdArray.hpp"
39
40namespace nc
41{
42 //============================================================================
43 // Method Description:
51 template<typename dtype>
52 NdArray<dtype> fromfile(const std::string& inFilename)
53 {
54 if (!std::filesystem::exists(inFilename))
55 {
56 THROW_INVALID_ARGUMENT_ERROR("input filename does not exist.\n\t" + inFilename);
57 }
58
59 // read in as binary file
60 std::ifstream file(inFilename.c_str(), std::ios::in | std::ios::binary);
61 if (!file.is_open())
62 {
63 THROW_INVALID_ARGUMENT_ERROR("unable to open file\n\t" + inFilename);
64 }
65
66 file.seekg(0, std::ifstream::end);
67 const auto fileSize = static_cast<uint64>(file.tellg());
68 file.seekg(0, std::ifstream::beg);
69
70 std::vector<char> fileBuffer;
71 fileBuffer.reserve(fileSize);
72 file.read(fileBuffer.data(), fileSize);
73
74 if (file.bad() || file.fail())
75 {
76 THROW_INVALID_ARGUMENT_ERROR("error occured while reading the file\n");
77 }
78
79 file.close();
80
81 NdArray<dtype> returnArray(reinterpret_cast<dtype*>(fileBuffer.data()), fileSize / sizeof(dtype));
82
83 return returnArray;
84 }
85
86 //============================================================================
87 // Method Description:
96 template<typename dtype>
97 NdArray<dtype> fromfile(const std::string& inFilename, const char inSep)
98 {
99 std::ifstream file(inFilename.c_str());
100 if (!file.is_open())
101 {
102 THROW_INVALID_ARGUMENT_ERROR("unable to open file\n\t" + inFilename);
103 }
104
105 std::stringstream buffer;
106 buffer << file.rdbuf();
107 file.close();
108
109 return fromstring<dtype>(buffer.str(), inSep);
110 }
111} // namespace nc
#define THROW_INVALID_ARGUMENT_ERROR(msg)
Definition Error.hpp:37
Holds 1D and 2D arrays, the main work horse of the NumCpp library.
Definition NdArrayCore.hpp:135
Definition Cartesian.hpp:39
std::uint64_t uint64
Definition Types.hpp:39
NdArray< dtype > fromstring(const std::string &inStr, const char inSep=' ')
Definition fromstring.hpp:47
NdArray< dtype > fromfile(const std::string &inFilename)
Definition fromfile.hpp:52