From: Laurent Mazet Date: Wed, 6 Dec 2023 09:55:11 +0000 (+0100) Subject: first process X-Git-Url: https://secure.softndesign.org/git/?p=indent.git;a=commitdiff_plain;h=222cc7151f4d4463a118db271469b3233079f350 first process --- diff --git a/indent.c b/indent.c index 2b88345..874eead 100644 --- a/indent.c +++ b/indent.c @@ -19,6 +19,15 @@ //#define BUFFERSIZE 4096 #define BUFFERSIZE 256 +#define TABSIZE 4 + +/* type definition */ + +typedef enum { + e_unknown = 0, + e_ansi, + e_kr +} cmode_t; /* gobal variables */ @@ -41,46 +50,53 @@ void usage (int ret) /* indent function */ -int indent (FILE *fin, FILE *fout) { - char buffer[BUFFERSIZE + 1] = {0}; +int indent (FILE *fin, FILE *fout, cmode_t cmode) { + char bufin[BUFFERSIZE + 1] = {0}; + char bufout[BUFFERSIZE * TABSIZE + 1] = {0}; + size_t i, nb; - char *pt = buffer; while (!feof (fin)) { - int nb = fread (pt, 1, BUFFERSIZE - (pt - buffer), fin); + + /* read file */ + nb = fread (bufin, 1, BUFFERSIZE, fin); VERBOSE (DEBUG, fprintf (stdout, "buffer: %d\n", nb)); - pt = buffer; - int i = 0; - while (pt[i] != '\0') { - if (pt[i++] == '\n') { - pt[i - 1] = 0; - - /* process line */ - char *line = pt; - VERBOSE (DEBUG, fprintf (stdout, "line: %d\n", strlen (line))); - VERBOSE (DEBUG, fprintf (stdout, "out: %s\n", line)); - int k = 0; - int begin = 0; - while (line[k] != '\0') { - switch (line[k]) { - case ' ': - case '\t': - if (begin) trailing++; - break; - default: - begin = 0; - - pt += i; - i = 0; + if (errno != 0) { + VERBOSE (ERROR, fprintf (stderr, "can't read file\n")); + exit (1); + } + + /* process line */ + char *ptin = bufin; + char *ptout = bufout; + while (*ptin != '\0') { + switch (*ptin) { + case '\t': + for (i = 0; i < TABSIZE; i++) { + *ptout++ = ' '; + } + break; + case '{': + case '}': + case ';': + *ptout++ = *ptin; + *ptout++ = '\n'; + break; + default: + *ptout++ = *ptin; } + ptin++; } - /* copy end buffer */ - int j = 0; - if (pt - buffer < BUFFERSIZE) { - for (i = pt - buffer; i < BUFFERSIZE; i++) { - buffer[j++] = *pt++; + ptout = '\0'; + + /* write file */ + ptout = bufout; + while ((nb = fread (ptout, 1, strlen (ptout), fout)) != strlen (ptout)) { + if (errno != 0) { + VERBOSE (ERROR, fprintf (stderr, "can't write file\n")); + exit (1); } - } - pt = buffer + j; + ptout += nb; + } } /* close all */ @@ -94,6 +110,7 @@ int indent (FILE *fin, FILE *fout) { int main (int argc, char *argv[]) { + cmode_t cmode = e_unknown; char *input = NULL; char *mode = "ansi"; char *output = NULL; @@ -155,7 +172,16 @@ int main (int argc, char *argv[]) fout = stdout; } - return indent (fin, fout); + /* check mode */ + if (strcmp (mode, "ansi") == 0) { + cmode = e_ansi; + } else if (strcmp (mode, "k&r") == 0) { + cmode = e_kr; + } else { + VERBOSE (ERROR, fprintf (stderr, "error: mode '%s' unknown\n", mode)); + } + + return indent (fin, fout, cmode); } // test: indent.exe -h