Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <errno.h>
- static const char separators[] = " \r\n\t,.-";
- void read_ints(char *filename, int **output_array, int *count)
- {
- FILE *f;
- int *array, allocated_size = 4;
- char line[256];
- if(!(f = fopen(filename, "r"))) {
- printf("unable to open '%s': %s\n", filename, strerror(errno));
- exit(1);
- }
- *count = 0;
- array = malloc(sizeof(int) * allocated_size);
- while(fgets(line, sizeof(line), f)) {
- for(char *token = strtok(line, separators); token; token = strtok(NULL, separators)) {
- array[(*count)++] = atoi(token);
- if(*count == allocated_size) {
- allocated_size *= 2;
- array = realloc(array, sizeof(int) * allocated_size);
- }
- }
- }
- fclose(f);
- *output_array = array;
- }
- int main()
- {
- int *some_ints, num_ints;
- read_ints("filename.txt", &some_ints, &num_ints);
- printf("read %d integers:\n", num_ints);
- for(int i = 0; i < num_ints; i++)
- printf("%d\n", some_ints[i]);
- free(some_ints);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement