Advertisement
Guest User

Untitled

a guest
May 20th, 2018
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.36 KB | None | 0 0
  1. #define IN_LINE_BUFSIZE 1024
  2. #define TOK_BUFSIZE 128
  3. #define TOK_DELIMITER " ,\t"
  4.  
  5. char *get_line(void) {
  6.     int bufsize = IN_LINE_BUFSIZE, pos = 0, c;
  7.     char *buffer = malloc(sizeof(char) * bufsize);
  8.    
  9.     if (!buffer) {
  10.         fprintf(stderr, "FATAL: failed to allocate memory");
  11.         exit(EXIT_FAILURE);
  12.     }
  13.    
  14.     while (1) {
  15.         c = getchar();
  16.        
  17.         if (c == EOF || c == '\n') {
  18.             buffer[pos] = '\0';
  19.             return buffer;
  20.         }
  21.         else {
  22.             buffer[pos] = c;
  23.         }
  24.         pos++;
  25.        
  26.         if (pos >= bufsize) {
  27.             bufsize += IN_LINE_BUFSIZE;
  28.             buffer = realloc(buffer, bufsize);
  29.             if (!buffer) {
  30.                 fprintf(stderr, "FATAL: failed to allocate memory");
  31.                 exit(EXIT_FAILURE);
  32.             }
  33.         }
  34.     }
  35. }
  36.  
  37. char **parse_line(char *line) {
  38.     int bufsize = TOK_BUFSIZE, pos = 0;
  39.     char **tokens = malloc(bufsize * sizeof(char*));
  40.     char *token;
  41.  
  42.     if (!tokens) {
  43.         fprintf(stderr, "FATAL: failed to allocate memory");
  44.         exit(EXIT_FAILURE);
  45.     }
  46.    
  47.     token = strtok(line, TOK_DELIMITER);
  48.     printf("Parse: token: %s\n", token);
  49.     while (token != NULL) {
  50.         tokens[pos] = token;
  51.         pos++;
  52.        
  53.         if (pos >= bufsize) {
  54.             bufsize += TOK_BUFSIZE;
  55.             tokens = realloc(tokens, bufsize * sizeof(char*));
  56.             if (!tokens) {
  57.                 fprintf(stderr, "FATAL: failed to allocate memory");
  58.                 exit(EXIT_FAILURE);
  59.             }
  60.         }
  61.        
  62.         token = strtok(NULL, TOK_DELIMITER);
  63.     }
  64.    
  65.     tokens[pos] = NULL;
  66.     return tokens;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement