使用不规则数组(ragged array)和agetline()将整个文件读入内存

1 #include <stdio.h>
2 #include <stdlib.h>
3 extern char *agetline(FILE *);
4 FILE *ifp;
5
6 /* assume ifp is open on input file */
7
8 char** lines = NULL;
9 size_t nalloc = 0;
10 size_t nlines = 0;
11 char *p;
12
13 while((p = agetline(ifp)) != NULL) {
14 if (nlines >= nalloc) {
15 nalloc += 50;
16 #ifdef SAFEREALLOC
17 lines = realloc(lines, nalloc * sizeof(char*));
18 #else
19 if(lines == NULL) /* in case pre - ANSI realloc */
20 lines = malloc(lines, nalloc * sizeof(char*));
21 else
22 lines = realloc(lines, nalloc * sizeof(char*));
23 #endif
24 if(lines == NULL) {
25 fprintf(stderr, "out of memeory");
26 exit(1);
27 }
28 }
29 lines[nlines++] = p;
30 }

posted on 2011-04-15 23:24  Cheney Shen  阅读(328)  评论(0编辑  收藏  举报

导航