Re: [NEWBIE][CODE] Files

From: Mike Breuer (mbreuer@new.rr.com)
Date: 03/26/01


> first off. when i do something = strtok() it doesnt work. i have to put it
> in sprintf

Based on your comment here, I suspect you are misusing strtok.  It
definately works.

-- snip --
> and the file looks like:
>
> CLAN: clannamehere
> LEAD: clanleader
> SPEL: clanspell
> CLAN: clannamehere
>
> here is the code that im tring it on:
>
>   FILE *ACLAN_FILE;
>    int num_lines = 0;
>   ACLAN_FILE=fopen("../lib/misc/clan", "r");
>   get_line(ACLAN_FILE, buf);
>   while (!feof(ACLAN_FILE)) {
>      num_lines++;
>      get_line(ACLAN_FILE,buf);
>   }
>   fclose(ACLAN_FILE);
>   ACLAN_FILE=fopen("../lib/misc/clan", "r");
>   buf2[0] = '\0';
>   get_line(ACLAN_FILE, buf);
>
>   while (!feof(ACLAN_FILE)) {
>      sprintf(buf2,"%s%s ",buf2, buf);
>      get_line(ACLAN_FILE, buf);
>      sprintf(buf, "%s", strtok(buf2, ": "));
>      sprintf(buf2, "%s\r\n", strtok(NULL, "\n"));
>      send_to_char(buf2, ch);
>   }
There are many problems in the above code.  The first while loop seems
completely unecessary, as you never use num_lines, and even if you use
it elsewhere you could get it in the second loop just as easily.

This list is not really the right place to go into all of the things
wrong with the second loop, so here is a quick rewrite to do what I
THINK you are trying to accomplish.  Note that this loop assumes you
stick fairly closely to the file layout you outlined above.  You also
need to add tests to ensure that the buffer does not overflow.

/* At the top of your function, add: */
char *ptr;

while (!feof(ACLAN_FILE)) {
  /* Parse off clan name */
  ptr = strtok(buf, ": ");
  if (strcmp(ptr, "CLAN") == 0)
    sprintf(buf2, "%s\r\nClan: %s ", buf2, strtok(NULL, "\r\n"));
  else if (strcmp(ptr, "LEAD") == 0)
    sprintf(buf2, "%sLeader: %s ", buf2, strtok(NULL, "\r\n"));
  else if (strcmp(ptr, "SPEL") == 0)
    sprintf(buf2, "%sSpell: %s ", buf2, strtok(NULL, "\r\n"));
  else {
    /* Some sort of appropiate error */
    send_to_char("Invalid argument in clan file!\r\n", ch);
    return;
  }
  get_line(ACLAN_FILE, buf);
}

>    page_string(ch->desc, buf2, 1);
>    fclose(ACLAN_FILE);

As I final comment, I would strongly encourage you to pursue some formal
training in C (class, tutorial, etc.), as you seem to be getting hung up
on some fundamentals.

Mike

--
   +---------------------------------------------------------------+
   | FAQ: http://qsilver.queensu.ca/~fletchra/Circle/list-faq.html |
   | Archives: http://post.queensu.ca/listserv/wwwarch/circle.html |
   +---------------------------------------------------------------+



This archive was generated by hypermail 2b30 : 12/04/01 PST