/*############################################################################ clean: Remove extraneous characters from text files. Written by Anastasios Kotsikonas. Usage: clean {file}+ */ # define MAX_BUF_LINES 100 # define MAX_LINE_LENGTH 133 # include # include main (argc, argv) int argc; char **argv; { FILE *fin, *fout; signed char command [80], line [MAX_LINE_LENGTH]; char *lines [MAX_LINE_LENGTH]; int i, ch, buf; long int obytes, newbytes; if (argc == 1) fprintf (stderr, "Usage: clean {file}+\nRemove extraneous characters from text files.\n"), exit (1); --argc; while (argc) { if ((fin = fopen (argv [argc], "r")) == NULL) { printf ("Unable to open input file '%s'\n", argv [argc]); fflush (stdout); --argc; continue; } if ((fout = fopen ("/tmp/clean.out", "w")) == NULL) { printf ("Unable to write to /tmp. File %s not cleaned.\n", argv [argc]); fflush (stdout); fclose (fin); --argc; continue; } obytes = newbytes = buf = 0; printf ("Cleaning '%s': ", argv [argc]); fflush (stdout); while (!feof (fin)) { line [0] = '\0'; fgets (line, MAX_LINE_LENGTH - 1, fin); if (strlen (line) > 0) { obytes += strlen (line); i = 0; while ((ch = line [i]) != '\n' && ch != '\0') { if (ch == '\n' || ch == '\r' || ch == '\t' || (ch >= ' ' && ch < 127)) ++i; else if (ch >= 0 && ch < 256) sprintf (line + i, "%s", line + i + 1); else { printf ("not a text file; file not cleaned.\n"); fflush (stdout); goto abort; } } newbytes += strlen (line); lines[buf] = (char *) malloc ((strlen (line) + 1) * sizeof (char)); strcpy (lines[buf], line); if (++buf > MAX_BUF_LINES - 1) { for (i = 0; i < buf; ++i) { if (fprintf (fout, "%s", lines[i]) < 0) { printf (" unable to write to /tmp anymore; file not cleaned.\n"); fflush (stdout); # ifdef unix unlink ("/tmp/clean.out"); # else command[0] = '\0'; sprintf (command, "del \\tmp\\clean.out"); system (command); # endif goto abort; } free (lines[i]); lines[i] = NULL; } buf = 0; } } } for (i = 0; i < buf; ++i) { if (fprintf (fout, "%s", lines[i]) < 0) { printf (" unable to write to /tmp anymore; file not cleaned.\n"); fflush (stdout); # ifdef unix unlink ("/tmp/clean.out"); # else command[0] = '\0'; sprintf (command, "del \\tmp\\clean.out"); system (command); # endif goto abort; } free (lines[i]); lines[i] = NULL; } buf = 0; printf ("%ld bytes before --> %ld bytes after", obytes, newbytes); if (obytes == newbytes) printf (": NO CHANGES"); printf ("\n"); fflush (stdout); fflush (fout); if (obytes != newbytes) command[0] = '\0', # ifdef unix sprintf (command, "mv /tmp/clean.out ./%s", argv [argc]), system (command); # else sprintf (command, "copy \\tmp\\clean.out .\\%s", argv [argc]), system (command); command[0] = '\0'; sprintf (command, "del \\tmp\\clean.out"); system (command); # endif abort: for (i = 0; i < buf; ++i) free (lines[i]); fclose (fin); fclose (fout); --argc; } }