From 0328de2ad645b1ea017d0482b4d637e9aa5eb40f Mon Sep 17 00:00:00 2001 From: Gleb Mazovetskiy Date: Wed, 12 Jun 2019 10:25:44 +0100 Subject: [PATCH] Read files using for better portability Refs https://github.com/sass/sassc-ruby/issues/128 --- src/file.cpp | 33 +++++++++++++++++++-------------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/src/file.cpp b/src/file.cpp index e1b8631e5..b7084dbc8 100644 --- a/src/file.cpp +++ b/src/file.cpp @@ -13,9 +13,8 @@ #else # include #endif -#include -#include #include +#include #include #include #include @@ -462,21 +461,27 @@ namespace Sass { // just convert from unsigned char* char* contents = (char*) pBuffer; #else + // Read the file using `` instead of `` for better portability. + // The `` header initializes `` and this buggy in GCC4/5 with static linking. + // See: + // https://www.spinics.net/lists/gcchelp/msg46851.html + // https://github.com/sass/sassc-ruby/issues/128 struct stat st; if (stat(path.c_str(), &st) == -1 || S_ISDIR(st.st_mode)) return 0; - std::ifstream file(path.c_str(), std::ios::in | std::ios::binary | std::ios::ate); - char* contents = 0; - if (file.is_open()) { - size_t size = file.tellg(); - // allocate an extra byte for the null char - // and another one for edge-cases in lexer - contents = (char*) malloc((size+2)*sizeof(char)); - file.seekg(0, std::ios::beg); - file.read(contents, size); - contents[size+0] = '\0'; - contents[size+1] = '\0'; - file.close(); + FILE* fd = std::fopen(path.c_str(), "rb"); + if (fd == nullptr) return nullptr; + const std::size_t size = st.st_size; + char* contents = static_cast(malloc(st.st_size + 2 * sizeof(char))); + if (std::fread(static_cast(contents), 1, size, fd) != size) { + free(contents); + return nullptr; } + if (std::fclose(fd) != 0) { + free(contents); + return nullptr; + } + contents[size] = '\0'; + contents[size + 1] = '\0'; #endif std::string extension; if (path.length() > 5) {