]> granicus.if.org Git - re2c/commitdiff
Fixed line endings in output files on Windows (#162, #163).
authorUlya Trofimovich <skvadrik@gmail.com>
Sun, 30 Jul 2017 16:45:30 +0000 (17:45 +0100)
committerUlya Trofimovich <skvadrik@gmail.com>
Sun, 30 Jul 2017 16:45:30 +0000 (17:45 +0100)
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

index f48706c7f83bbe114b52058dd02c7fa008a2a4b5..b78cf560e213451e32721f0a84e05f2b83afb461 100644 (file)
@@ -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<std::streamsize>(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<std::string> &global_types,
                filename = "<stdout>";
                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<std::string> &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;