#include #include #include #include #include #include #include #include void usage (char * progname) { fprintf (stderr, "usage: %s [ -c | -a | -s ] file format\n", progname); exit (1); } int ncol; int * fieldwidth; int recordwidth; int readformat (char * f) { int i, j; ncol = 1; for (i=0; f[i]; i++) if (f[i] == ':') ncol++; recordwidth = 0; fieldwidth = malloc (ncol * sizeof (int)); assert (fieldwidth); j = 0; while (1) { if (sscanf (f, "%d", &fieldwidth[j] ) != 1) return 0; recordwidth += fieldwidth[j]; j++; while (isdigit ((int)*f)) f++; if (*f == 0) break; if (*f != ':') return 0; f++; } if (j != ncol) return 0; return 1; } void create (char * file) { char * buf, * record; int i, len, offset; int fd; buf = malloc ((recordwidth+1)*sizeof (char)); record = malloc ((recordwidth+1)*sizeof (char)); assert (buf); assert (record); offset = 0; i = 0; while (i < ncol) { printf ("Beschreibung %d. Feld (maximal %d Zeichen: ", i+1, fieldwidth[i]); fgets (buf, recordwidth+1, stdin); len = strlen (buf); if (buf[len-1] == '\n') { buf[len-1] = 0; len--; } if (len > fieldwidth[i]) { fprintf (stderr, "Beschreibung zu lang\n"); continue; } strncpy (record+offset, buf, fieldwidth[i]); offset += fieldwidth[i]; i++; } free (buf); fd = open (file, O_WRONLY | O_CREAT | O_EXCL, 0666); if (fd < 0) { perror ("open"); exit (1); } if (write (fd, record, recordwidth) < 0) { perror ("write"); exit (1); } if (close (fd) < 0) { perror ("close"); exit (1); } free (record); printf ("OK. Datenbank mit dem Namen %s erzeugt\n", file); } void show (char * file) { int i, fd, ret, offset; char * buf; char * buf2; fd = open (file, O_RDONLY); if (fd < 0) { perror ("open"); exit (1); } buf = malloc (recordwidth * sizeof (char)); buf2 = malloc ((recordwidth+1)* sizeof (char)); assert (buf); while (1) { ret = read (fd, buf, recordwidth); if (ret < 0) { perror ("read"); } if (ret == 0) break; if (ret != recordwidth) { fprintf (stderr, "Datenbank kaputt\n"); exit (1); } offset = 0; for (i=0; i fieldwidth[i]) { fprintf (stderr, "Text zu lang\n"); continue; } strncpy (record+offset, buf, fieldwidth[i]); offset += fieldwidth[i]; i++; } free (desc); free (desc2); free (buf); fd = open (file, O_WRONLY | O_APPEND); if (fd < 0) { perror ("open"); exit (1); } if (write (fd, record, recordwidth) < 0) { perror ("write"); exit (1); } if (close (fd) < 0) { perror ("close"); exit (1); } free (record); printf ("OK. Datensatz zu %s hinzugefuegt\n", file); } int main (int argc, char *argv[]) { if (argc != 4) usage (argv[0]); if (argv[1][0] != '-') usage (argv[0]); if (!argv[1][1] || argv[1][2]) usage (argv[0]); if (!readformat (argv[3])) usage (argv[0]); switch (argv[1][1]) { case 'c': create (argv[2]); break; case 's': show (argv[2]); break; case 'a': append (argv[2]); break; default: usage (argv[0]); } return 0; }