Created
March 15, 2011 15:11
-
-
Save pr4v33n/870850 to your computer and use it in GitHub Desktop.
Reading integers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <glob.h> | |
#include <errno.h> | |
int main(int argc, char *argv[]) | |
{ | |
char pattern[] = "/tmp/*.txt"; | |
glob_t globbuf; | |
FILE *file; | |
int i, num, n = 0, max = 10; | |
int *numbers = malloc(sizeof(int) * max); | |
glob(pattern, 0, NULL, &globbuf); | |
char buf[80]; | |
for (i = 0; i < globbuf.gl_pathc; i++) | |
{ | |
if ((file = fopen(globbuf.gl_pathv[i], "r")) != NULL) | |
{ | |
while (fscanf(file, "%s\n", buf) == 1) | |
{ | |
char *p = buf; | |
errno = 0; | |
num = (int) strtoul(buf, &p, 10); | |
if((errno != 0) || (p == buf) || (*p != 0)) { | |
continue; | |
} | |
numbers[n] = num; | |
n++; | |
if (n >= max) | |
{ | |
max = max * 2; | |
numbers = realloc(numbers, sizeof(int) * max); | |
} | |
} | |
fclose(file); | |
} | |
} | |
globfree(&globbuf); | |
printf("Collected numbers:\n"); | |
for (i = 0; i < n; i++) | |
{ | |
printf("%d\n", numbers[i]); | |
} | |
free(numbers); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment