tags:

views:

45

answers:

2

Hi, I'm trying to read a file which uses 2 colons as a delimiter using fscanf. Example:

Input

:watermelon::a tasty fruit::potato::a vegetable::

Each of the produce and definitions are delimited by a colon. I'm trying to iterate through this list so that I can print out the definitions and output.

Output: (through a printf)

watermelon

a tasty fruit

potato

a vegetable

I'm not sure how to do the iterations through a while loop and it's just printing watermelon over and over again at the moment.

Thanks for your help!

A: 

Using strtok() is the key:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main () {
    FILE * fl;
    long fl_size;
    char * buffer;
    size_t res;

    fl = fopen ( "fruits.txt" , "r+" );
    if (fl==NULL) {
        fprintf (stderr, "File error\n"); 
        exit (1);
    }

    fseek (fl , 0 , SEEK_END);
    fl_size = ftell (fl);
    rewind (fl);

    buffer = (char*) malloc (sizeof(char)*fl_size);
    if (buffer == NULL) {
        fputs ("Memory error",stderr); 
        exit (2);
    }

    res = fread (buffer,1,fl_size,fl);
    if (res != fl_size) {
        fputs ("Reading error",stderr); 
        exit (3);
    }

    /*
     * THIS IS THE PART THAT IS IMPORTANT FOR THE QUESTION!!
     */
    char * strtok_res;
    strtok_res = strtok(buffer, "::");
    while (strtok_res != NULL)
    {
        printf ("%s\n", strtok_res);
        strtok_res = strtok (NULL, "::");
    }
    /*
     * DONE!
     */



    fclose (fl);
    free (buffer);
    return 0;
}
simurg
A: 

If you can be sure that the file is formatted as

:<produce>::<description>::<produce>::<description>:...

Then you could use a loop with this fscanf format:

char produce[100], description[100];
if ((fscanf(file, ":%99[^:]::%99[^:]:", produce, description) != 2)
{
    /* Handle read error or EOF */
}
Bart van Ingen Schenau