home *** CD-ROM | disk | FTP | other *** search
Wrap
/*----------------------------------------------------------+ | stripcr.c -- 5/15/1992 public domain | | by Alex Matulich, Unicorn Research Corporation | | Strip CR characters from a text file, leaving only LF's. | +----------------------------------------------------------*/ #define OUTBUFSIZ 16384 #include <stdio.h> #include <stdlib.h> /* for malloc() */ #define CR '\x0D' unsigned short replace, bufptr = 0; signed char *buf = NULL; FILE *infile, *outfile; long inpos = 0L, outpos = 0L; /* file position trackers */ int writebuf(void); void main(int argc, char *argv[]) { unsigned short err = 0; signed char ch; if (argc != 3 && argc != 2) { fputs("StripCR by Unicorn Research Corporation\nStrip CR characters from text files that use the CR+LF combination.\n\nUsage: StripCR infile [outfile]\n\nIf outfile is omitted, then infile will be replaced.\n", stdout); return; } if((infile = fopen( argv[1], (replace = (argc == 2)) ? "rb+" : "rb" )) == NULL) { fputs("Could not open input file.\n", stdout); return; } if (replace) outfile = infile; else if ((outfile = fopen( argv[2], "wb" )) == NULL) { fputs("Could not open output file.\n", stdout); fclose(infile); return; } if ((buf = (signed char *)malloc(OUTBUFSIZ)) == NULL) { fputs("Not enough memory!\n", stdout); goto cleanup; } while ((ch = fgetc(infile)) != EOF) { ++inpos; /* position of next character in input file */ if (ch != CR) { buf[bufptr++] = ch; if (bufptr == OUTBUFSIZ) if (err = writebuf()) break; } } if (!err && bufptr) err = writebuf(); if (err == 1) fputs("Error writing output file.\n", stdout); else if (err == 2) fputs("Error reading input file.\n", stdout); else if (replace) { fseek(outfile, outpos, 0); fputc('\x1A', outfile); /* output a ctrl-Z */ fputs(argv[1], stdout); fputs(" is now stripped of CR's.\nDelete all text past the ctrl-Z character.\n", stdout); } else { fputs("Stripped file ", stdout); fputs(argv[2], stdout); fputs(" successfully created.\n", stdout); } cleanup: free(buf); fclose(infile); if (!replace) fclose(outfile); } /* write the buffer to the output file, when full or when done */ int writebuf() { unsigned short i = 0; if (replace) if (fseek(outfile, outpos, 0)) return 1; while (i < bufptr) if (fputc(buf[i++], outfile) == EOF) return 1; outpos += bufptr; if (replace) if (fseek(infile, inpos, 0)) return 2; bufptr = 0; return 0; }