|
| 1 | +/* |
| 2 | + * Convert all line endings to LF (Unix style) |
| 3 | + * |
| 4 | + * This tool ensures consistent line endings before processing with inliner. |
| 5 | + * It converts CR-only (old Mac) and CRLF (Windows) to LF (Unix). |
| 6 | + */ |
| 7 | + |
| 8 | +#include <stdbool.h> |
| 9 | +#include <stdio.h> |
| 10 | +#include <stdlib.h> |
| 11 | + |
| 12 | +int main(int argc, char *argv[]) |
| 13 | +{ |
| 14 | + if (argc != 3) { |
| 15 | + fprintf(stderr, "Usage: %s <input> <output>\n", argv[0]); |
| 16 | + return 1; |
| 17 | + } |
| 18 | + |
| 19 | + FILE *input = fopen(argv[1], "rb"); |
| 20 | + if (!input) { |
| 21 | + fprintf(stderr, "Error: Cannot open input file '%s'\n", argv[1]); |
| 22 | + return 1; |
| 23 | + } |
| 24 | + |
| 25 | + FILE *output = fopen(argv[2], "wb"); |
| 26 | + if (!output) { |
| 27 | + fprintf(stderr, "Error: Cannot create output file '%s'\n", argv[2]); |
| 28 | + fclose(input); |
| 29 | + return 1; |
| 30 | + } |
| 31 | + |
| 32 | + int c; |
| 33 | + int prev_cr = 0; |
| 34 | + bool has_crlf = false; |
| 35 | + bool has_lf = false; |
| 36 | + bool has_cr_only = false; |
| 37 | + |
| 38 | + while ((c = fgetc(input)) != EOF) { |
| 39 | + if (c == '\r') { |
| 40 | + /* Mark that we saw a CR, but don't output it yet */ |
| 41 | + prev_cr = 1; |
| 42 | + } else if (c == '\n') { |
| 43 | + if (prev_cr) { |
| 44 | + /* CRLF sequence - output single LF */ |
| 45 | + has_crlf = true; |
| 46 | + } else { |
| 47 | + /* LF only */ |
| 48 | + has_lf = true; |
| 49 | + } |
| 50 | + fputc('\n', output); |
| 51 | + prev_cr = 0; |
| 52 | + } else { |
| 53 | + if (prev_cr) { |
| 54 | + /* CR not followed by LF - convert to LF */ |
| 55 | + fputc('\n', output); |
| 56 | + has_cr_only = true; |
| 57 | + } |
| 58 | + fputc(c, output); |
| 59 | + prev_cr = 0; |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + /* Handle CR at end of file */ |
| 64 | + if (prev_cr) { |
| 65 | + fputc('\n', output); |
| 66 | + has_cr_only = true; |
| 67 | + } |
| 68 | + |
| 69 | + fclose(input); |
| 70 | + fclose(output); |
| 71 | + |
| 72 | + /* Report what was found and converted */ |
| 73 | + if (has_cr_only) { |
| 74 | + fprintf(stderr, |
| 75 | + "Warning: Converted CR-only line endings to LF in '%s'\n", |
| 76 | + argv[1]); |
| 77 | + } |
| 78 | + if ((has_crlf && has_lf) || (has_crlf && has_cr_only) || |
| 79 | + (has_lf && has_cr_only)) { |
| 80 | + fprintf(stderr, "Warning: Converted mixed line endings to LF in '%s'\n", |
| 81 | + argv[1]); |
| 82 | + } |
| 83 | + |
| 84 | + return 0; |
| 85 | +} |
0 commit comments