From 6831c35f53cd4db7196e6fd3c0a26ef5a2e75d38 Mon Sep 17 00:00:00 2001 From: Ulya Trofimovich Date: Sun, 30 Jul 2017 17:45:30 +0100 Subject: [PATCH] Fixed line endings in output files on Windows (#162, #163). This fix consists of two issues, both reported and fixed by pauloscustodio. 1. #162 "Open text files with "wb" causes issues on Windows" Text files need to be opened for writing with "w", so that stdio does the right thing in respect to the correct line endings for the current OS. ("\r\n" in Windows, "\n" in Linux). 2. #163 "Reading files with "rb" causes issues in Windows" re2c reads input files in binary mode and writes the generated output in text mode. This caused CR LF conversion to CR CR LF on Windows: first CR comes from reading input in binary mode, second CR is added when writing output in text mode. This only happened to those parts of input which are not transformed by re2c: we used to copy-paste verbatim, now we patch line endings. Now we convert all line endings to LF before writing the generated code to file. --- re2c/src/code/output.cc | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/re2c/src/code/output.cc b/re2c/src/code/output.cc index f48706c7..b78cf560 100644 --- a/re2c/src/code/output.cc +++ b/re2c/src/code/output.cc @@ -89,7 +89,20 @@ OutputFile &OutputFile::wraw(const char *s, const char *e) { if (block().opts->target == TARGET_CODE) { insert_code(); - stream().write(s, static_cast(e - s)); + + // convert CR LF to LF + std::ostream &o = stream(); + for (const char *p = s;; ++p) { + std::streamsize l = p - s; + if (p == e) { + o.write(s, l); + break; + } else if (*p == '\n') { + if (p > s && p[-1] == '\r') --l; + o.write(s, l); + s = p; + } + } } return *this; } @@ -400,7 +413,7 @@ bool OutputFile::emit(const uniq_vector_t &global_types, filename = ""; file = stdout; } else { - file = fopen(filename.c_str(), "wb"); + file = fopen(filename.c_str(), "w"); if (!file) { error("cannot open output file: %s", filename.c_str()); return false; @@ -500,7 +513,7 @@ bool HeaderFile::emit(const opt_t *opts, const uniq_vector_t &types const std::string &filename = opts->header_file; if (filename.empty()) return true; - FILE *file = fopen(filename.c_str(), "wb"); + FILE *file = fopen(filename.c_str(), "w"); if (!file) { error("cannot open header file: %s", filename.c_str()); return false; -- 2.50.1