/* $Id: 8bitscan.c 40 2007-10-20 09:18:22Z dleigh $ * * Dylan Leigh 2007 -=- This program is in the public domain. * Hyperlinks are appreciated but not required. * * * 8 Bit Character Scanner * * For each file given as an argument, scan it for 8-bit characters. * Print matches like so: * , line : , , ... * * Should handle files with no terminating newline, and lines of any * length up to UNSIGNED_MAX. * * BUGS: Undefined behaviour may result if: * - There are more than UNSIGNED_MAX lines in the file * - There are more than UNSIGNED_MAX characters in a line * (On most systems this equates to 4GB of newlines, or * characters on a line, so this shouldn't cause problems) * */ #include #include int main(int argc, char** argv) { unsigned fnum = 1; // index to filename in argv FILE * file = NULL; // file we are working on if (argc < 2) // no args, do usage and quit { fprintf(stderr, "Usage: %s file [file] [file] ...\n", argv[0]); exit(EXIT_FAILURE); } for (fnum = 1; fnum < argc; fnum++) { unsigned matches = 0; // matches in current line file = fopen(argv[fnum],"r"); if (NULL == file) // can't open file { perror(argv[fnum]); } else { unsigned lnum = 0; // line number in current file unsigned cnum = 0; // character count in current line int c; // char read from file (int for errors) while (EOF != (c = fgetc(file))) { cnum++; if (c > 127) // 8 bit character { if (matches) { matches++; printf(", %d", cnum); } else // first match on this line, print file, line { matches++; printf("%s line %d: %d", argv[fnum], lnum, cnum); } } else // not 8 bit { if ('\n' == c) { /* Terminate the printed line (if exists), reset * matches and char count, increment line num. */ if (matches) printf("\n"); matches = 0; cnum = 0; lnum++; } } } // end while read line if (feof(file)) { // Special case: last line has no newline // check to see if we need to end the printf if (matches) { printf("\n"); } } else // file read error { perror(argv[fnum]); } } // end else on opening file } //end for fnum return EXIT_SUCCESS; } // end main ()