|
|
1.1 ! root 1: /* ! 2: * char * getline(ifp, lineno) FILE *ifp; int *lineno; ! 3: * ! 4: * Function to get lines from an input file. ! 5: * Returns the address of the line, or NULL for eof. ! 6: * ! 7: * lineno should usually be started at 1. lineno will ! 8: * be incremented by the number of lines in the previous call. ! 9: * Thus lineno will be the number of the line just gotten. ! 10: * ! 11: * # to end of line is passed. unless # is first char ! 12: * \ whitespace through end of line is passed. ! 13: */ ! 14: #include <misc.h> ! 15: ! 16: static char outSpace[] = "Out of space"; ! 17: static char *line = NULL; ! 18: static int i; ! 19: static int size = 0; ! 20: static int oldline = 0; ! 21: ! 22: static void ! 23: addchr(c) ! 24: { ! 25: extern char *realloc(); ! 26: ! 27: while (i >= size) ! 28: if (NULL == (line = realloc(line, size += 80))) ! 29: fatal("Out of space"); ! 30: line[i++] = c; ! 31: } ! 32: ! 33: char * ! 34: getline(ifp, lineno) ! 35: FILE *ifp; ! 36: int *lineno; ! 37: { ! 38: int c, octacc, octcnt; ! 39: enum state { normal, incont, incomm, fullcomm, bsl } state; ! 40: ! 41: *lineno += oldline; ! 42: for (state = normal, oldline = i = 0;;) { ! 43: if (EOF == (c = fgetc(ifp))) { ! 44: if (i) ! 45: fprintf(stderr, ! 46: "line %d truncated at end\n", ! 47: *lineno + oldline); ! 48: return (NULL); ! 49: } ! 50: ! 51: switch (state) { ! 52: case normal: ! 53: switch (c) { ! 54: case '\\': ! 55: state = bsl; ! 56: continue; ! 57: ! 58: case '\n': ! 59: oldline++; ! 60: addchr('\n'); ! 61: addchr(0); ! 62: return (line); ! 63: ! 64: case '#': ! 65: if (i) { ! 66: state = incomm; ! 67: continue; ! 68: } ! 69: state = fullcomm; ! 70: } ! 71: addchr(c); ! 72: continue; ! 73: ! 74: case incont: ! 75: if ('\n' == c) { ! 76: oldline++; ! 77: state = normal; ! 78: } ! 79: continue; ! 80: ! 81: case fullcomm: ! 82: if ('\n' == c) { ! 83: state = normal; ! 84: oldline++; ! 85: addchr('\n'); ! 86: addchr(0); ! 87: return (line); ! 88: } ! 89: addchr(c); ! 90: continue; ! 91: ! 92: case incomm: ! 93: if ('\n' == c) { ! 94: state = normal; ! 95: oldline++; ! 96: addchr('\n'); ! 97: addchr(0); ! 98: return (line); ! 99: } ! 100: continue; ! 101: ! 102: case bsl: ! 103: switch (c) { ! 104: case ' ': ! 105: case '\t': ! 106: state = incont; ! 107: continue; ! 108: ! 109: case '\n': ! 110: oldline++; ! 111: state = normal; ! 112: continue; ! 113: } ! 114: state = normal; ! 115: addchr('\\'); ! 116: addchr(c); ! 117: continue; ! 118: } ! 119: } ! 120: ! 121: } ! 122: ! 123: #ifdef TEST ! 124: main() ! 125: { ! 126: int line = 1; ! 127: char *got; ! 128: ! 129: for (;;) { ! 130: if (NULL == (got = getline(stdin, &line))) ! 131: exit(0); ! 132: printf("%d - %s\n", line, got); ! 133: } ! 134: } ! 135: #endif
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.