Skip to content

Commit

Permalink
Read files using <cstdio> for better portability
Browse files Browse the repository at this point in the history
  • Loading branch information
glebm committed Jun 12, 2019
1 parent a46a281 commit 0328de2
Showing 1 changed file with 19 additions and 14 deletions.
33 changes: 19 additions & 14 deletions src/file.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,8 @@
#else
# include <unistd.h>
#endif
#include <iostream>
#include <fstream>
#include <cctype>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <sys/stat.h>
Expand Down Expand Up @@ -462,21 +461,27 @@ namespace Sass {
// just convert from unsigned char*
char* contents = (char*) pBuffer;
#else
// Read the file using `<cstdio>` instead of `<fstream>` for better portability.
// The `<fstream>` header initializes `<locale>` 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<char*>(malloc(st.st_size + 2 * sizeof(char)));
if (std::fread(static_cast<void*>(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) {
Expand Down

0 comments on commit 0328de2

Please sign in to comment.