Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BUG FIX: CSV Reader now reads UTF-8 text files correctly. #1205

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 35 additions & 2 deletions src/simplnx/Utilities/FileUtilities.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

#include <fmt/format.h>

#include <array>
#include <filesystem>
#include <fstream>

Expand Down Expand Up @@ -95,7 +96,7 @@ Result<> ValidateCSVFile(const std::string& filePath)
}

// Obtain the file size
const size_t fileSize = fs::file_size(absPath);
usize fileSize = fs::file_size(absPath);

// Open the file
std::ifstream in(absPath.c_str(), std::ios_base::binary);
Expand All @@ -104,7 +105,18 @@ Result<> ValidateCSVFile(const std::string& filePath)
return MakeErrorResult(-301, fmt::format("Could not open file for reading: {}", absPath.string()));
}

size_t actualSize = bufferSize;
auto isUtf8 = IsUtf8(absPath);
if(isUtf8.first)
{
// The file is UTF8 with a BOM marker, so read the first 3 bytes and dump them.
char a = '\0';
char b = '\0';
char c = '\0';
in >> a >> b >> c;
fileSize -= 3;
}

usize actualSize = bufferSize;
if(fileSize <= bufferSize)
{
actualSize = fileSize;
Expand Down Expand Up @@ -230,4 +242,25 @@ Result<> ValidateDirectoryWritePermission(const fs::path& path, bool isFile)
}
return MakeErrorResult(-8, fmt::format("ValidateDirectoryWritePermission() Error: User does not have write permissions to path '{}'", path.string()));
}

std::pair<bool, int32> IsUtf8(const fs::path& filePath)
{
FILE* f = fopen(filePath.string().c_str(), "rb");
if(nullptr == f)
{
return {false, -1};
}
std::array<uint8, 3> buf = {0, 0, 0};
if(fread(buf.data(), 1, 3, f) != 3)
{
std::ignore = fclose(f);
return {false, -1};
}
std::ignore = fclose(f);
if(buf[0] == 0xEF && buf[1] == 0xBB && buf[2] == 0xBF)
{
return {true, 0};
}
return {false, 0};
}
} // namespace nx::core::FileUtilities
7 changes: 7 additions & 0 deletions src/simplnx/Utilities/FileUtilities.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,11 @@ SIMPLNX_EXPORT bool HasWriteAccess(const std::string& path);
* @return
*/
SIMPLNX_EXPORT Result<> ValidateDirectoryWritePermission(const fs::path& path, bool isFile);

/**
* @brief
* @param filePath
* @return
*/
SIMPLNX_EXPORT std::pair<bool, int32> IsUtf8(const fs::path& filePath);
} // namespace nx::core::FileUtilities
Loading