/* ** uncrlf.c - A small program to convert text files to the UNIX ** end-of-line convention. Handles PC (CR-LF), Mac (CR) ** and strange (LF-CR) files automatically. ** ** Copyright (c) 2000 Peter Eriksson ** ** This program is free software; you can redistribute it and/or ** modify it as you wish - as long as you don't claim that you wrote ** it. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ** ** Usage: ** uncrlf [... ] ** */ #include #include #include int lf_seen = 0; int cr_seen = 0; char * my_dirname(const char *path, char *buf) { char *cp; cp = strrchr(path, '/'); if (cp == NULL) { strcpy(buf, "."); return buf; } strncpy(buf, path, cp-path); buf[cp-path] = '\0'; return buf; } int fix_crlf(FILE *in, FILE *out) { int c; while ((c = getc(in)) != EOF) switch (c) { case 10: if (lf_seen) putc(10, out); else if (cr_seen) { putc(10, out); cr_seen = 0; } else lf_seen = 1; break; case 13: if (cr_seen) putc(10, out); else if (lf_seen) { putc(10, out); lf_seen = 0; } else cr_seen = 1; break; default: if (lf_seen) { putc(10, out); lf_seen = 0; } if (cr_seen) { putc(10, out); cr_seen = 0; } putc(c, out); } if (lf_seen) { putc(10, out); lf_seen = 0; } if (cr_seen) { putc(10, out); cr_seen = 0; } return 0; } int main(int argc, char *argv[]) { int i; char buf[2048]; FILE *in, *out; if (argc == 1) { if (fix_crlf(stdin, stdout) < 0) { fprintf(stderr, "%s: conversion failed\n", argv[0]); exit(1); } } else { for (i = 1; i < argc; i++) { my_dirname(argv[i], buf); sprintf(buf+strlen(buf), "/.tmp.%d", getpid()); in = fopen(argv[i], "r"); if (in == NULL) { fprintf(stderr, "%s: fopen: %s: %s\n", argv[0], argv[i], strerror(errno)); exit(1); } out = fopen(buf, "w"); if (out == NULL) { fprintf(stderr, "%s: fopen: %s: %s\n", argv[0], buf, strerror(errno)); exit(1); } if (fix_crlf(in, out) < 0) { fprintf(stderr, "%s: conversion failed\n", argv[0]); exit(1); } fclose(in); fclose(out); if (rename(buf, argv[i]) < 0) { fprintf(stderr, "%s: rename: %s -> %s: %s", argv[0], buf, argv[i], strerror(errno)); exit(1); } } } return 0; }