Parsing a String into Tokens Using strcspn, Part 3

Dave Sinkula 0 Tallied Votes 720 Views Share
#include <stdio.h>
#include <string.h>

int main(void)
{
   static const char filename[] = "file.txt"; /* the name of a file to open */
   FILE *file = fopen(filename, "r"); /* try to open the file */
   if ( file != NULL )
   {
      char line[BUFSIZ]; /* space to read a line into */
      /*
       * Create an array of strings: here each line may be broken up into up
       * to 20 strings of up to 32 characters. Try changing it to 10 to hit
       * the "no more room" message.
       */
      char data[20][32];
      while ( fgets(line, sizeof line, file) != NULL ) /* read each line */
      {
         size_t i = 0, size;
         char *token = line;
         fputs(line, stdout);
         for ( ;; )
         {
            size_t len = strcspn(token, ";\n"); /* search for delimiters */
            /*
             * Use sprint to copy the text into a char array.
             */
            sprintf(data[i], "%.*s", (int)len, token);

            token += len; /* advance pointer by the length of the found text */
            if ( *token == '\0' )
            {
               break; /* advanced to the terminating null character */
            }
            ++token; /* skip the delimiter */

            /* advance the index into the string array */
            if ( ++i >= sizeof data / sizeof *data )
            {
               puts("no more room");
               break;
            }
         }
         /*
          * Display the results.
          */
         for ( size = i, i = 0; i < size; ++i )
         {
            printf("data[%d] = \"%s\"\n", (int)i, data[i]);
         }
         puts("---");
      }
      fclose(file);
   }
   else
   {
      perror(filename); /* why didn't the file open? */
   }
   return 0;
}

/* file.txt
2;31May2005;23:59:00;100.2.1.12;log;accept;;eth9;inbound;VPN-1
FireWall-1;;100.1.20.130;172.30.7.114;icmp;191;;;8;0;;;;
*/

/* my output
2;31May2005;23:59:00;100.2.1.12;log;accept;;eth9;inbound;VPN-1
data[0] = "2"
data[1] = "31May2005"
data[2] = "23:59:00"
data[3] = "100.2.1.12"
data[4] = "log"
data[5] = "accept"
data[6] = ""
data[7] = "eth9"
data[8] = "inbound"
data[9] = "VPN-1"
---
FireWall-1;;100.1.20.130;172.30.7.114;icmp;191;;;8;0;;;;
data[0] = "FireWall-1"
data[1] = ""
data[2] = "100.1.20.130"
data[3] = "172.30.7.114"
data[4] = "icmp"
data[5] = "191"
data[6] = ""
data[7] = ""
data[8] = "8"
data[9] = "0"
data[10] = ""
data[11] = ""
data[12] = ""
data[13] = ""
*/