Skip to content

Commit

Permalink
Update file reading in proxy_slave.cpp
Browse files Browse the repository at this point in the history
Changed the method to read data from the file in the "proxy_slave.cpp" file. Refactored the read_data function to use std::ifstream instead of FILE for readability and to handle exceptions better. Now the function directly returns the data read from the file instead of taking a reference. It's also been changed to throw an exception if the file fails to open or read, making error handling more explicit. This approach is more robust and easier to debug.
  • Loading branch information
markaren committed Jul 1, 2023
1 parent d7e5946 commit 2083178
Showing 1 changed file with 15 additions and 12 deletions.
27 changes: 15 additions & 12 deletions src/ecos/fmi/proxy/proxy_slave.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

#include <chrono>
#include <cstdio>
#include <fstream>
#include <proxyfmu/thrift/BootService.h>
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/transport/TSocket.h>
Expand All @@ -21,18 +22,21 @@ using namespace proxyfmu::thrift;
namespace
{

void read_data(std::string const& fileName, std::string& data)
std::string read_data(std::string const& fileName)
{
FILE* file = fopen(fileName.c_str(), "rb");
if (file == nullptr) return;
fseek(file, 0, SEEK_END);
long int size = ftell(file);
fclose(file);
file = fopen(fileName.c_str(), "rb");
std::ifstream file(fileName, std::ios::binary | std::ios::ate);
if (!file) {
throw std::runtime_error("Failed to open file: " + fileName);
}
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);

std::vector<char> buffer(size);
if (!file.read(buffer.data(), size)) {
throw std::runtime_error("Failed to read file: " + fileName);
}

data.resize(size);
[[maybe_unused]] size_t bytes_read = fread(data.data(), sizeof(unsigned char), size, file);
fclose(file);
return {buffer.begin(), buffer.end()};
}

} // namespace
Expand Down Expand Up @@ -67,8 +71,7 @@ proxy_slave::proxy_slave(
auto client = std::make_shared<BootServiceClient>(protocol);
transport->open();

std::string data;
read_data(fmuPath.string(), data);
std::string data = read_data(fmuPath.string());

const std::string fmuName = std::filesystem::path(fmuPath).stem().string();
port = client->loadFromBinaryData(fmuName, instanceName, data);
Expand Down

0 comments on commit 2083178

Please sign in to comment.