logoISU  

CS 456 - Systems Programming

Spring 2024

Displaying ./code/apr11/strtok_ex.c

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

#define K   1024

/**
 * Uses the strtok() function to split the string in buf into individual
 * strings.
 */
void tokenize(char *buf)
{
  int w = 0;
  char *token = strtok(buf, " \t\n");
  for(; token != NULL; token = strtok(NULL, " \t\n")) {
    printf("%d = '%s'\n", w++, token);
  }
}

int main(void)
{
  int r;
  char buf[K+1];

  /**
   * Read a line of text from stdin using the read syscall.
   * Using fgets() would probably be better.
   */
  while ( (r = read(STDIN_FILENO, buf, K)) > 0) {
    // Null terminate the string, because read() does not do this.
    buf[r] = '\0';
    tokenize(buf);
  }

  return 0;
}