Aggiunto esempio di server per le fortunes, basato sulle fifo.
[gapil.git] / sources / FortuneParse.c
diff --git a/sources/FortuneParse.c b/sources/FortuneParse.c
new file mode 100644 (file)
index 0000000..962ffc5
--- /dev/null
@@ -0,0 +1,83 @@
+/* FortuneParse.c
+ * 
+ * Copyright (C) 2002 Simone Piccardi
+ * 
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ * 
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * General Public License for more details.
+ * 
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/****************************************************************
+ *
+ * Routine FortuneParse
+ * parse fortunes from a fortune file
+ *
+ * Author: Simone Piccardi
+ * Aug. 2002
+ *
+ * Usage: int FortuneParse(char *file, char ** fortune, int n);
+ * Read n fortunes from fortune file file, and put it into the
+ * string array fortune
+ *
+ * $Id: FortuneParse.c,v 1.1 2002/08/18 10:34:10 piccardi Exp $
+ *
+ ****************************************************************/
+/* 
+ * Include needed headers
+ */
+#include <sys/types.h>   /* predefined types */
+#include <sys/stat.h>    /*  */
+#include <unistd.h>      /* include unix standard library */
+#include <stdio.h>       /* include standard I/O library */
+#include <stdlib.h>     /* standard library */
+#include <string.h>     /* ANSI C standard string */
+#include <errno.h>      /* error definitions */
+#include <fcntl.h>      /*  */
+
+/* Subroutines declaration */
+extern void usage(void);
+
+int FortuneParse(char *file, char **fortune, int n)
+{
+/* Variables definition */
+    FILE *fortunefile;
+    char line[80];
+    int i;
+    /* 
+     *  fortune file scanning, read string in memory 
+     */
+    fortunefile = fopen(file,"r");
+    if (fortunefile == NULL) {                       /* on open error exit */
+       perror("Opening fortune file");
+       exit(-1);
+    }
+    i = 0;
+    do {
+       if (!fgets(line, 80, fortunefile)) {
+           if (feof(fortunefile)) break;
+           perror("Read error");
+           exit(-1);
+       }
+       if (line[0]=='\n') {
+           if (fortune[i]!=NULL) i++;
+           continue;
+       }
+       if (fortune[i]==NULL) {
+           fortune[i] = (char *) malloc(strlen(line)+1);
+           strncpy(fortune[i], line, strlen(line)+1);
+       } else {
+           fortune[i] = (char *) realloc(fortune[i], strlen(line)+1);
+           strncat(fortune[i], line, strlen(line)+1);
+       }
+    } while (i<n);
+    return i;
+}