Skip to content

Commit 0328de2

Browse files
committed
Read files using <cstdio> for better portability
Refs sass/sassc-ruby#128
1 parent a46a281 commit 0328de2

File tree

1 file changed

+19
-14
lines changed

1 file changed

+19
-14
lines changed

src/file.cpp

+19-14
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,8 @@
1313
#else
1414
# include <unistd.h>
1515
#endif
16-
#include <iostream>
17-
#include <fstream>
1816
#include <cctype>
17+
#include <cstdio>
1918
#include <vector>
2019
#include <algorithm>
2120
#include <sys/stat.h>
@@ -462,21 +461,27 @@ namespace Sass {
462461
// just convert from unsigned char*
463462
char* contents = (char*) pBuffer;
464463
#else
464+
// Read the file using `<cstdio>` instead of `<fstream>` for better portability.
465+
// The `<fstream>` header initializes `<locale>` and this buggy in GCC4/5 with static linking.
466+
// See:
467+
// https://www.spinics.net/lists/gcchelp/msg46851.html
468+
// https://github.com/sass/sassc-ruby/issues/128
465469
struct stat st;
466470
if (stat(path.c_str(), &st) == -1 || S_ISDIR(st.st_mode)) return 0;
467-
std::ifstream file(path.c_str(), std::ios::in | std::ios::binary | std::ios::ate);
468-
char* contents = 0;
469-
if (file.is_open()) {
470-
size_t size = file.tellg();
471-
// allocate an extra byte for the null char
472-
// and another one for edge-cases in lexer
473-
contents = (char*) malloc((size+2)*sizeof(char));
474-
file.seekg(0, std::ios::beg);
475-
file.read(contents, size);
476-
contents[size+0] = '\0';
477-
contents[size+1] = '\0';
478-
file.close();
471+
FILE* fd = std::fopen(path.c_str(), "rb");
472+
if (fd == nullptr) return nullptr;
473+
const std::size_t size = st.st_size;
474+
char* contents = static_cast<char*>(malloc(st.st_size + 2 * sizeof(char)));
475+
if (std::fread(static_cast<void*>(contents), 1, size, fd) != size) {
476+
free(contents);
477+
return nullptr;
479478
}
479+
if (std::fclose(fd) != 0) {
480+
free(contents);
481+
return nullptr;
482+
}
483+
contents[size] = '\0';
484+
contents[size + 1] = '\0';
480485
#endif
481486
std::string extension;
482487
if (path.length() > 5) {

0 commit comments

Comments
 (0)