-
Notifications
You must be signed in to change notification settings - Fork 0
/
falloc.c
52 lines (38 loc) · 1.22 KB
/
falloc.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// falloc() read a file into memory
//
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "falloc.h"
int falloc(FILE *fp);
char **fal_gp;
extern char buf[BUFSIZ];
/* falloc: read a file into dynamically allocated arrays for every line
*
* buf: global buffer for temporary line storage while data is being read
* fal_gp: pointer to start of arrays
* returns: number of lines read in or, -1 for no lines or memory error
*
*/
int falloc(FILE *fp) {
char **hap_ln; // array of pointers
// that point to each line read in
int lines = 0;
hap_ln = (char **)malloc(sizeof(int *));
// read input lines into dynamically allocated arrays
while (fgets(buf, sizeof(buf), fp) != NULL) {
char **hap_new = (char **)realloc(hap_ln,
(lines+1)*sizeof(char **));
if (hap_new == NULL) {
fprintf(stderr, "%s: memory error\n", __func__);
return -1;
}
hap_ln = hap_new;
hap_ln[lines] = (char *)malloc(sizeof(buf)+1);
memcpy(hap_ln[lines], buf, sizeof(buf));
lines++;
}
fal_gp = hap_ln;
return lines;
}