Advertisement
eXFq7GJ1cC

Untitled

Mar 14th, 2012
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.16 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <errno.h>
  5.  
  6. static const char separators[] = " \r\n\t,.-";
  7.  
  8. void read_ints(char *filename, int **output_array, int *count)
  9. {
  10.     FILE *f;
  11.     int *array, allocated_size = 4;
  12.     char line[256];
  13.    
  14.     if(!(f = fopen(filename, "r"))) {
  15.         printf("unable to open '%s': %s\n", filename, strerror(errno));
  16.         exit(1);
  17.     }
  18.    
  19.     *count = 0;
  20.     array = malloc(sizeof(int) * allocated_size);
  21.     while(fgets(line, sizeof(line), f)) {
  22.         for(char *token = strtok(line, separators); token; token = strtok(NULL, separators)) {
  23.             array[(*count)++] = atoi(token);
  24.             if(*count == allocated_size) {
  25.                 allocated_size *= 2;
  26.                 array = realloc(array, sizeof(int) * allocated_size);
  27.             }
  28.         }
  29.     }
  30.     fclose(f);
  31.    
  32.     *output_array = array;
  33. }
  34.  
  35. int main()
  36. {
  37.     int *some_ints, num_ints;
  38.  
  39.     read_ints("filename.txt", &some_ints, &num_ints);
  40.     printf("read %d integers:\n", num_ints);
  41.     for(int i = 0; i < num_ints; i++)
  42.         printf("%d\n", some_ints[i]);
  43.  
  44.     free(some_ints);
  45.     return 0;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement