Re: fscanf and linked list problem

From: Al Bowers (xabowers_at_rapidsys.com)
Date: 08/29/04


Date: Sun, 29 Aug 2004 09:31:36 -0400


Kay wrote:
> 1) If i want to read data from a txt file,
> eg John; 23; a
> Mary; 16; i
> How can I read the above data stopping reading b4 each semi-colon and
> save it in three different variables ?
>
> 2) If I enter a number, can I use to call a particular node ?
> eg enter a number: 3
> calling node of number 3
> is it possible ?
>

You could try reading a line of text from the file with function
fgets. Then use function sscanf to parse the line. The specifier
%s can be used if the name has no spaces in it. Otherwise you can
use the scanset, []. If you want the number to be type int use
%d for the specifier, or %u if unsigned. Then for the last use %c.

For an example look at function AddBIO_ARR in the code below.

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

#define LINE_MAX 80

typedef struct BIO
{
    char name[64];
    unsigned age;
    char paylocation;
} BIO;

typedef struct BIO_ARR
{
    BIO *bio;
    unsigned cnt;
}BIO_ARR;

int AddBIO_ARR(BIO_ARR *p, const char *s);
void PrintBIO_ARR( BIO_ARR *p);
void FreeBIO_ARR( BIO_ARR *p);

int main(void)
{
    char fline[LINE_MAX];
    struct BIO_ARR Prez = {NULL,0}; /* Initializes with no Bio Info */
    FILE *fp;

    if((fp = fopen("test.txt","r")) == NULL)
    {
       puts("Unable to open the file");
       exit(EXIT_FAILURE);
    }
    while(NULL != fgets(fline,sizeof fline,fp))
    AddBIO_ARR(&Prez,fline);
    fclose(fp);
    PrintBIO_ARR(&Prez);
    FreeBIO_ARR(&Prez);
    return 0;
}

int AddBIO_ARR(BIO_ARR *p, const char *s)
{
    BIO *tmp;

    if((tmp = realloc(p->bio,(sizeof *p->bio)*(p->cnt+1))) == NULL)
       return 0;
    p->bio = tmp;
    if(3 != sscanf(s,"%63[^;]; %u; %c",p->bio[p->cnt].name,
              &p->bio[p->cnt].age, &p->bio[p->cnt].paylocation))
       return 0;
    p->cnt++;
    return 1;
}

void PrintBIO_ARR( BIO_ARR *p)
{
    unsigned i;

    for(i = 0; i < p->cnt;i++)
    printf("Name: %s\n Age: %u\nPLoc: %c\n\n",
                 p->bio[i].name, p->bio[i].age,
                 p->bio[i].paylocation);
    return;
}

void FreeBIO_ARR( BIO_ARR *p)
{
    free(p->bio);
    p->bio = NULL;
    p->cnt = 0;
    return;
}

-- 
Al Bowers
Tampa, Fl USA
mailto: xabowers@myrapidsys.com (remove the x to send email)
http://www.geocities.com/abowers822/


Relevant Pages