Information wants to be free...

CRLF to LF Converter

This is a really simple program, but it's always missing on the Windows platform, where it is needed the most. Because of this, I will include both the source code and a Windows binary here for easy access.

Notice that the program does not use standard in/out; this has to do with the strange Windows behaviour on binary files. Instead, the files must be opened directly using "binary mode".

Here's the binary (compiled with MinGW) and here's the source:

#include <stdio.h>

int main(int argc, char *argv[])
{
  int c, last;
  FILE *in, *out;

  if (argc != 3) {
    fprintf(stderr, "Usage: %s <infile> <outfile>\n", argv[0]);
    return 1;
  }

  in = fopen(argv[1], "rb");
  if (in == NULL) {
    fprintf(stderr, "Error: Cannot open input file.\n");
    return 1;
  }

  out = fopen(argv[2], "wb");
  if (out == NULL) {
    fprintf(stderr, "Error: Cannot open output file.\n");
    fclose(in);
    return 1;
  }

  last = -1;
  while ((c = fgetc(in)) != EOF) {
    if (c == '\n' && last == '\r') {
      fputc(c, out);
      last = -1;
    } else {
      if (last != -1)
        fputc(last, out);
      last = c;
    }
  }
  if (last != -1)
    fputc(last, out);

  fclose(in);
  fclose(out);

  return 0;
}
          


Topic: Scripts and Code, by Kjetil @ 07/05-2011, Article Link