NumCpp  2.10.1
A Templatized Header Only C++ Implementation of the Python NumPy Library
fromfile.hpp
Go to the documentation of this file.
1 #pragma once
29 
30 #include <filesystem>
31 #include <fstream>
32 #include <memory>
33 #include <sstream>
34 #include <string>
35 
38 #include "NumCpp/Core/Types.hpp"
40 #include "NumCpp/NdArray.hpp"
41 
42 namespace nc
43 {
44  //============================================================================
45  // Method Description:
53  template<typename dtype>
54  NdArray<dtype> fromfile(const std::string& inFilename)
55  {
56  if (!std::filesystem::exists(inFilename))
57  {
58  THROW_INVALID_ARGUMENT_ERROR("input filename does not exist.\n\t" + inFilename);
59  }
60 
61  // read in as binary file
62  std::ifstream file(inFilename.c_str(), std::ios::in | std::ios::binary);
63  if (!file.is_open())
64  {
65  THROW_INVALID_ARGUMENT_ERROR("unable to open file\n\t" + inFilename);
66  }
67 
68  file.seekg(0, std::ifstream::end);
69  const uint32 fileSize = static_cast<uint32>(file.tellg());
70  file.seekg(0, std::ifstream::beg);
71 
72  std::vector<char> fileBuffer;
73  fileBuffer.reserve(fileSize);
74  file.read(fileBuffer.data(), fileSize);
75 
76  if (file.bad() || file.fail())
77  {
78  THROW_INVALID_ARGUMENT_ERROR("error occured while reading the file");
79  }
80 
81  file.close();
82 
83  NdArray<dtype> returnArray(reinterpret_cast<dtype*>(fileBuffer.data()), fileSize / sizeof(dtype));
84 
85  return returnArray;
86  }
87 
88  //============================================================================
89  // Method Description:
98  template<typename dtype>
99  NdArray<dtype> fromfile(const std::string& inFilename, const char inSep)
100  {
101  std::ifstream file(inFilename.c_str());
102  if (!file.is_open())
103  {
104  THROW_INVALID_ARGUMENT_ERROR("unable to open file\n\t" + inFilename);
105  }
106 
107  std::stringstream buffer;
108  buffer << file.rdbuf();
109  file.close();
110 
111  return fromstring<dtype>(buffer.str(), inSep);
112  }
113 } // 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:138
Definition: Coordinate.hpp:45
NdArray< dtype > fromfile(const std::string &inFilename)
Definition: fromfile.hpp:54
std::uint32_t uint32
Definition: Types.hpp:40