3

I'm making a program that accepts a number and then parses the a file to return the name associated with that number. It's mostly done, but there's just one last step. Right now, my program correctly finds the line associated with the given number by checking the first token of every line. Here's a snippet of the code that matters:

  while (fgets(line, 50, f)) {
      tok = strtok(line, " ");

      if (n == atoi(tok))
      {
          printf(" %s\n", tok);
          return 0;
      }
  }

Right now it just prints the first token, which is great because that means it found the right line. However, I need it to print the last token, but I can't figure out how to do that with strtok(). Could someone help me out?

Matt
  • 74,352
  • 26
  • 153
  • 180
Bob
  • 715
  • 2
  • 11
  • 32
  • 2
    Duplicate question: http://stackoverflow.com/questions/32822988/get-the-last-token-of-a-string-in-c – Saskia Sep 04 '16 at 22:23

1 Answers1

2

Once you find the line you want, keep calling strtok with NULL for the first parameter, but keep track of what the prior return value was. Once strtok returns NULL, the pointer to the previous token points to the last one:

  if (number == atoi(token)) {
      char *prev = token;
      printf(" %s\n", token);
      while ((token=strtok(NULL," ")) != NULL) {
        printf(" %s\n", token);
        prev = token;
      }
      printf("last: %s\n", prev);
      return 0;
    }

Contents of /proc/interrupts:

           CPU0       
  0:  723903927    IO-APIC-edge  timer
  1:      10105    IO-APIC-edge  i8042
  6:          5    IO-APIC-edge  floppy
  7:          0    IO-APIC-edge  parport0
  8:          1    IO-APIC-edge  rtc
  9:          0   IO-APIC-level  acpi
 12:      24023    IO-APIC-edge  i8042
 14:     221198    IO-APIC-edge  ide0
 15:    6473219    IO-APIC-edge  ide1
169:     637825   IO-APIC-level  eth0

Output with argument "6":

 6:
last: floppy
dbush
  • 205,898
  • 23
  • 218
  • 273