-
Notifications
You must be signed in to change notification settings - Fork 0
/
fields.c
107 lines (92 loc) · 1.9 KB
/
fields.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "fields.h"
#define talloc(ty, sz) (ty *) malloc (sz * sizeof(ty))
#define strdup(s) ((char *) strcpy(talloc(char, strlen(s)+1), s))
static IS make_inputstruct(char *filename, char *key)
/* "f" for regular file or stdin if filename is NULL */
/* "p" if filename is a command for popen */
{
IS is;
int file;
if (strcmp(key, "f") == 0) {
file = 1;
} else if (strcmp(key, "p") == 0) {
file = 0;
} else {
return NULL;
}
is = talloc(struct inputstruct, 1);
is->text1[MAXLEN-1] = '\0';
is->NF = 0;
is->line = 0;
if (filename == NULL) {
is->name = "stdin";
is->f = stdin;
} else {
is->name = filename;
is->file = file;
if (file) {
is->f = fopen(filename, "r");
} else {
is->f = popen(filename, "r");
}
if (is->f == NULL) {
free(is);
return NULL;
}
}
return is;
}
IS new_inputstruct(char *filename) /* use NULL for stdin. Calls malloc */
{
return make_inputstruct(filename, "f");
}
IS pipe_inputstruct(char *command)
{
return make_inputstruct(command, "p");
}
int get_line(IS is)
{
int i, len;
int f;
char *tmp;
char lastchar;
char *line;
is->NF = 0;
if (fgets(is->text1, MAXLEN-1, is->f) == NULL) {
is->NF = -1;
return -1;
}
is->line++;
strcpy(is->text2, is->text1);
line = is->text2;
lastchar = ' ';
for (i = 0; line[i] != '\0' && i < MAXLEN-1; i++) {
if (isspace(line[i])) {
lastchar = line[i];
line[i] = '\0';
} else {
if (isspace(lastchar)) {
is->fields[is->NF] = line+i;
is->NF++;
}
lastchar = line[i];
}
}
return is->NF;
}
void jettison_inputstruct(IS is)
{
if (is->f != stdin) {
if (is->file) {
fclose(is->f);
} else {
pclose(is->f);
}
}
free(is);
return;
}