Debian Codegraph @

easel/esl_fileparser.c

raw symbols SCIP
1 /* A simple token-based file parsing system.
2 *
3 * Contents:
4 * 1. The ESL_FILEPARSER object and its API.
5 * 2. Private functions.
6 * 3. Unit tests.
7 * 4. Test driver.
8 * 5. Examples.
9 */
10 #include <esl_config.h>
11
12 #include <stdlib.h>
13 #include <stdio.h>
14 #include <string.h>
15 #include <ctype.h>
16
17 #include "easel.h"
18 #include "esl_fileparser.h"
19
20 static int nextline(ESL_FILEPARSER *efp);
21
22 /*****************************************************************
23 * 1. The ESL_FILEPARSER object and its API.
24 *****************************************************************/
25
26 /* Function: esl_fileparser_Open()
27 * Incept: SRE, Tue Apr 3 08:09:56 2007 [Janelia]
28 *
29 * Purpose: Opens <filename> for reading.
30 *
31 * As a special case, if <filename> is "-", set up the
32 * fileparser to read and parse <stdin>.
33 *
34 * <envvar> is optional name of an environment variable,
35 * such as <BLASTDB>. This environment variable contains a
36 * colon-delimited list of directories in which the
37 * <filename> may lie relative to. We looks first relative
38 * to the current working directory, then in any
39 * directories specified by <envvar>. If <envvar> is <NULL>,
40 * we only look in the current working directory.
41 *
42 * Args: filename - filename, relative path, or fully qualified path
43 * envvar - optional environment variable name to find
44 * colon-delimited list of directories <filename>
45 * may reside in; or <NULL>
46 * ret_efp - RETURN: opened <ESL_FILEPARSER>
47 *
48 * Returns: <eslOK> on success, and <ret_fp> points
49 * to a new <ESL_FILEPARSER> object.
50 *
51 * Returns <eslENOTFOUND> if <filename> can't
52 * be opened for reading, and <ret_fp> is set
53 * to <NULL>.
54 *
55 * Throws: <eslEMEM> on allocation failure.
56 */
57 int
58 esl_fileparser_Open(const char *filename, const char *envvar, ESL_FILEPARSER **ret_efp)
59 {
60 int status;
61 ESL_FILEPARSER *efp = NULL;
62
63 if ((efp = esl_fileparser_Create(NULL)) == NULL) { status = eslEMEM; goto ERROR; }
64
65 if (strcmp(filename, "-") == 0)
66 efp->fp = stdin;
67 else if ((efp->fp = fopen(filename, "r")) != NULL) {
68 if ((status = esl_strdup(filename, -1, &(efp->filename))) != eslOK) goto ERROR;
69 }
70 else if ((status = esl_FileEnvOpen(filename, envvar, &(efp->fp), &(efp->filename))) != eslOK)
71 { status = eslENOTFOUND; goto ERROR; }
72
73 *ret_efp = efp;
74 return eslOK;
75
76 ERROR:
77 esl_fileparser_Close(efp);
78 *ret_efp = NULL;
79 return status;
80 }
81
82
83 /* Function: esl_fileparser_Create()
84 * Incept: SRE, Fri Jul 9 12:50:29 2004 [St. Louis]
85 *
86 * Purpose: Take an open file <fp>, and transform it to
87 * a fileparser object -- preparing to parse it
88 * one whitespace-delimited field at a time.
89 *
90 * Args: fp - open FILE to parse
91 *
92 * Returns: a new <ESL_FILEPARSER> object, which must be
93 * free'd by the caller with <esl_fileparser_Destroy()>.
94 *
95 * Throws: <eslEMEM> if an allocation failed.
96 *
97 * Xref: STL8 p.56.
98 */
99 ESL_FILEPARSER *
100 esl_fileparser_Create(FILE *fp)
101 {
102 int status;
103 ESL_FILEPARSER *efp = NULL;
104
105 ESL_ALLOC(efp, sizeof(ESL_FILEPARSER));
106 efp->fp = fp;
107 efp->buf = NULL;
108 efp->buflen = 0;
109 efp->s = NULL;
110 efp->commentchar = '\0';
111 efp->filename = NULL;
112 efp->linenumber = 0;
113 efp->errbuf[0] = '\0';
114 efp->is_buffer = FALSE;
115 efp->mem_buffer = NULL;
116 efp->mem_size = 0;
117 efp->mem_pos = 0;
118 return efp;
119
120 ERROR:
121 esl_fileparser_Destroy(efp);
122 return NULL;
123 }
124
125
126 /* Function: esl_fileparser_CreateMapped()
127 * Incept: MSF, Mon Aug 16 2010 [Janelia]
128 *
129 * Purpose: Sets up a memory buffer to be parsed with the file parser
130 * routines.
131 *
132 * Args: fp - open FILE to parse
133 *
134 * Returns: a new <ESL_FILEPARSER> object, which must be
135 * free'd by the caller with <esl_fileparser_Destroy()>.
136 *
137 * Throws: <eslEMEM> if an allocation failed.
138 *
139 * Xref: STL8 p.56.
140 */
141 ESL_FILEPARSER *
142 esl_fileparser_CreateMapped(const void *buffer, int size)
143 {
144 ESL_FILEPARSER *efp = NULL;
145
146 if ((efp = esl_fileparser_Create(NULL)) == NULL) return NULL;
147
148 efp->is_buffer = TRUE;
149 efp->mem_buffer = buffer;
150 efp->mem_size = size;
151 return efp;
152 }
153
154
155
156
157 /* Function: esl_fileparser_SetCommentChar()
158 *
159 * Purpose: Defines a single character <c> for comments. Anything
160 * on a line following this character is ignored
161 * when parsing.
162 *
163 * Args: efp - open fileparser
164 * c - comment character ('#', for example)
165 *
166 * Returns: <eslOK> on success.
167 */
168 int
169 esl_fileparser_SetCommentChar(ESL_FILEPARSER *efp, char c)
170 {
171 efp->commentchar = c;
172 return eslOK;
173 }
174
175
176
177 /* Function: esl_fileparser_GetToken()
178 * Incept: SRE, Fri Jul 9 13:03:50 2004 [St. Louis]
179 *
180 * Purpose: Sets a pointer to the next field in the
181 * file we're parsing.
182 *
183 * The <opt_tok> pointer is into an internal line buffer
184 * that may be invalidated upon the next call to a
185 * <fileparser> function. If you want to store it, make a
186 * copy.
187 *
188 * Args: efp - open fileparser
189 * opt_tok - optRETURN: ptr to next field
190 * opt_toklen - optRETURN: length of tok.
191 *
192 * Returns: <eslOK> if <tok>, <toklen> contain valid data.
193 * <eslEOF> on normal end-of-file.
194 *
195 * Throws: <eslEMEM> if an allocation fails.
196 *
197 * Xref: STL8 p.56.
198 */
199 int
200 esl_fileparser_GetToken(ESL_FILEPARSER *efp, char **opt_tok, int *opt_toklen)
201 {
202 char *tok = NULL;
203 int toklen = 0;
204 int tokcode;
205 int fcode;
206 int goodtok;
207
208 if (opt_tok) *opt_tok = NULL;
209 if (opt_toklen) *opt_toklen = 0;
210
211 /* First, make sure we have a line loaded.
212 * On the first call to GetToken, we won't.
213 */
214 if (efp->buf == NULL) {
215 fcode = nextline(efp);
216 if (fcode != eslOK) return fcode;
217 }
218
219 /* Start strtok()'ing this line to try to find token.
220 * If we don't find one, keep loading lines until we
221 * do, or we run out of data.
222 * efp->s was set either by nextline() or previous GetToken().
223 */
224 do {
225 goodtok = FALSE;
226 tokcode = esl_strtok_adv(&(efp->s), " \t\r\n", &tok, &toklen, NULL);
227 if (tokcode == eslEOL || (tokcode == eslOK && *tok == efp->commentchar))
228 {
229 fcode = nextline(efp);
230 if (fcode != eslOK) return fcode;
231 }
232 else if (tokcode == eslOK) goodtok = TRUE;
233 else ESL_FAIL(tokcode, efp->errbuf, "esl_strtok() failed");
234 } while (! goodtok);
235
236 if (opt_tok) *opt_tok = tok;
237 if (opt_toklen) *opt_toklen = toklen;
238 return eslOK;
239 }
240
241
242 /* Function: esl_fileparser_NextLine()
243 * Incept: SRE, Tue Apr 3 08:27:22 2007 [Janelia]
244 *
245 * Purpose: Advance the parser to the next non-blank, non-comment
246 * data line that contains at least one token.
247 *
248 * Upon return, <efp->buf> is a data-containing line, and
249 * <efp->s> points to the first non-whitespace character on
250 * it. A line-based parser can work on one or both of these.
251 *
252 * A line-oriented but token-based parser will call
253 * <esl_fileparser_GetTokenOnLine()> to extract successive
254 * tokens from it.
255 *
256 * A pure token-based parser will generally not call
257 * <_NextLine()>. The only reason would be to skip the
258 * remainder of a line it's in the middle of parsing, and
259 * advance to the next one -- but that's a sort of
260 * line-oriented thing to do.
261 *
262 * Returns: <eslOK> on success.
263 * <eslEOF> if no more data lines remain in the file.
264 *
265 * Throws: <eslEMEM> on allocation error.
266 */
267 int
268 esl_fileparser_NextLine(ESL_FILEPARSER *efp)
269 {
270 int status;
271
272 while ((status = nextline(efp)) == eslOK)
273 {
274 while (*(efp->s) != '\0' && isspace(*(efp->s))) efp->s++;
275 if (*(efp->s) != '\0' && *efp->s != efp->commentchar) break;
276 }
277 if (status == eslEOF) return status;
278 if (status != eslOK) ESL_FAIL(status, efp->errbuf, "nextline() failed");
279 return eslOK;
280 }
281
282
283 /* Function: esl_fileparser_NextLinePeeked()
284 * Synopsis: Read the next line, prepending a peek.
285 * Incept: SRE, Wed Oct 15 10:08:37 2008 [Janelia]
286 *
287 * Purpose: Sometimes we need to peek at the start of an input stream
288 * to see whether it is in a binary format, before we start
289 * parsing it as ASCII lines. When this happens, the caller
290 * will typically have used <fread()> to read a fixed
291 * number of bytes from the input stream, checked to see if
292 * they are a magic number representing a binary format,
293 * and found that they are not. The caller then wants to
294 * switch to reading in ASCII format with the <fileparser>
295 * API, but with those bytes included on the first
296 * line. Because the file might start with comments or
297 * blank lines that need to be skipped, we want to deal
298 * with the peeked data in the context of the
299 * <ESL_FILEPARSER>. The caller cannot simply close and
300 * reopen the stream, because the stream may be a pipe
301 * (<stdin> or <gzip -dc> for example).
302 *
303 * The caller passes the bytes it peeked at with <fread()>
304 * in <prefix>, and the number of bytes it peeked at in
305 * <plen>.
306 *
307 * The parser is advanced to the next non-blank,
308 * non-comment data line that contains at least one token,
309 * taking the prepended <prefix> into account.
310 *
311 * There is a significant flaw in this mechanism, and as a
312 * result the caller must be able to guarantee the
313 * following limitation. The first data-containing line
314 * must be longer than <prefix>. It is sufficient for the
315 * first data token to be longer than <prefix>.
316 * (Equivalently, if <prefix> contains any data token, it
317 * must not contain any newline \verb+\n+ after that data.) The
318 * reason is that we need to avoid a situation where the
319 * concatenated prefix+nextline contains more than one data
320 * line, because other routines in the module assume that
321 * <efp->buf> is a single \verb+\n+-terminated line of input. For
322 * example: HMMER save files either start with a 4-byte
323 * binary magic number, or with "HMMER", and "HMMER" is
324 * longer than 4 bytes.
325 *
326 * Args: efp - open fileparser
327 * prefix - bytes that caller obtained by peeking with fread()
328 * plen - number of bytes in prefix
329 *
330 * Returns: <eslOK> on success.
331 * <eslEOF> if no more tokens remain in the file.
332 *
333 * Throws: <eslEMEM> on allocation error.
334 *
335 * Xref: For an example, see HMMER's HMM save file input.
336 */
337 int
338 esl_fileparser_NextLinePeeked(ESL_FILEPARSER *efp, char *prefix, int plen)
339 {
340 int blen;
341 int status;
342
343 /* First, make buf = the first line again, by prepending <prefix>. */
344 if ((status = nextline(efp)) != eslOK) goto ERROR; /* EOF, EMEM */
345 blen = strlen(efp->buf);
346
347 if (blen + plen + 1 > efp->buflen) {
348 ESL_REALLOC(efp->buf, sizeof(char) * (blen + plen + 1));
349 efp->buflen = blen + plen + 1;
350 }
351 memmove(efp->buf+plen, efp->buf, blen+1);
352 memcpy(efp->buf, prefix, plen);
353 efp->s = efp->buf;
354
355 while (*(efp->s) != '\0' && isspace(*(efp->s))) efp->s++;
356 if (*(efp->s) != '\0' && *efp->s != efp->commentchar) return eslOK;
357 else return esl_fileparser_NextLine(efp);
358
359 ERROR:
360 return status;
361 }
362
363
364
365
366 /* Function: esl_fileparser_GetTokenOnLine()
367 * Incept: SRE, Tue Apr 3 08:46:59 2007 [Janelia]
368 *
369 * Purpose: Same as <esl_fileparser_GetToken()>, except that it only
370 * retrieves tokens from the line that the parser is
371 * on. When it runs out of tokens on the line, it returns
372 * <eslEOL>. This allows a caller to count the tokens on a
373 * line (whereas <GetToken()> reads through newlines
374 * silently).
375 *
376 * The <opt_tok> pointer is into an internal line buffer
377 * that may be invalidated upon the next call to a
378 * <fileparser> function. If you want to store it, make a
379 * copy.
380 *
381 * Normally, a call to <esl_fileparser_GetTokenOnLine()>
382 * would be preceded by <esl_fileparser_NextLine()> to
383 * position the parser on the next data line with at least
384 * one token on it. However, you could also conceivably
385 * call <esl_fileparser_GetTokenOnLine()> after one or more
386 * calls to <esl_fileparser_GetToken()>, to get remaining
387 * tokens from a given line. What you can't do is to call
388 * <esl_fileparser_GetTokenOnLine()> immediately after
389 * opening a file; the parser won't have a line loaded yet.
390 * (In this case, it would return <eslEOL>.)
391 *
392 * Returns: <eslOK> on success, and the token and its length are
393 * in <opt_tok> and <opt_toklen>.
394 *
395 * Returns <eslEOL> if no more tokens exist on the line;
396 * in this case <opt_tok> is set to <NULL> and <opt_toklen>
397 * to 0.
398 */
399 int
400 esl_fileparser_GetTokenOnLine(ESL_FILEPARSER *efp, char **opt_tok, int *opt_toklen)
401 {
402 char *tok = NULL;
403 int toklen = 0;
404 int status;
405
406 /* No line loaded? Then we can't find any token on it. */
407 if (efp->buf == NULL) { status = eslEOL; goto ERROR; }
408
409 /* Find next token in the line that's already loaded in the parser. */
410 status = esl_strtok_adv(&(efp->s), " \t\r\n", &tok, &toklen, NULL);
411 if (status == eslEOL) goto ERROR;
412 if (status != eslOK) goto ERROR;
413 if (status == eslOK && *tok == efp->commentchar) { status = eslEOL; goto ERROR; }
414
415 if (opt_tok) *opt_tok = tok;
416 if (opt_toklen) *opt_toklen = toklen;
417 return eslOK;
418
419 ERROR:
420 if (opt_tok) *opt_tok = NULL;
421 if (opt_toklen) *opt_toklen = 0;
422 return status;
423 }
424
425
426 /* Function: esl_fileparser_GetRemainingLine()
427 * Synopsis: Returns pointer to the rest of the current line.
428 * Incept: SRE, Mon Oct 13 08:59:26 2008 [Janelia]
429 *
430 * Purpose: Set a pointer <*ret_s> to the rest of the current line
431 * held by the fileparser <efp>. Trailing newline char,
432 * if any, is removed.
433 *
434 * Because <ret_s> points to internal storage in the
435 * fileparser, the caller should be finished with it before
436 * making its next call to any fileparser function.
437 *
438 * Any comment characters on the rest of the line are
439 * ignored: this is designed for a case where the rest of
440 * the line is to be read as free text.
441 *
442 * Args: efp - fileparser
443 * ret_s - RETURN: pointer to the remainder of the line
444 *
445 * Returns: <eslOK> on success.
446 * <eslEOL> if nothing remains on the line, and <*ret_s>
447 * is <NULL>.
448 *
449 * Throws: (no abnormal error conditions)
450 */
451 int
452 esl_fileparser_GetRemainingLine(ESL_FILEPARSER *efp, char **ret_s)
453 {
454 /* No line loaded? Then we can't find anything on it. */
455 if (efp->buf == NULL) { *ret_s = NULL; return eslEOL; }
456
457 /* skip leading whitespace */
458 while (isspace(*(efp->s))) efp->s++;
459
460 /* Return everything to end of line as a "token", stripping newline */
461 return esl_strtok(&(efp->s), "\r\n", ret_s);
462 }
463
464
465 /* Function: esl_fileparser_Destroy()
466 * Incept: SRE, Fri Jul 9 13:22:36 2004 [St. Louis]
467 *
468 * Purpose: Frees an open <ESL_FILEPARSER>. The original fp is
469 * still open - whoever opened it is still
470 * responsible for closing it.
471 *
472 * Xref: STL8 p.56.
473 */
474 void
475 esl_fileparser_Destroy(ESL_FILEPARSER *efp)
476 {
477 if (efp) {
478 if (efp->buf != NULL) free(efp->buf);
479 free(efp);
480 }
481 }
482
483 /* Function: esl_fileparser_Close()
484 * Incept: SRE, Tue Apr 3 08:18:11 2007 [Janelia]
485 *
486 * Purpose: Closes an open <ESL_FILEPARSER>, including the
487 * file it opened.
488 */
489 void
490 esl_fileparser_Close(ESL_FILEPARSER *efp)
491 {
492 if (efp == NULL) return;
493
494 if (efp->fp != NULL && efp->fp != stdin) fclose(efp->fp);
495 if (efp->filename != NULL) free(efp->filename);
496 esl_fileparser_Destroy(efp);
497 }
498
499
500
501 /*****************************************************************
502 * 2. Private functions
503 *****************************************************************/
504
505 /* nextline()
506 *
507 * Purpose: Skip the file parser to the next line (for instance,
508 * if an end-of-line comment is found). The new line might
509 * have no tokens on it.
510 *
511 * Args: efp - open file parser
512 *
513 * Returns: eslOK: success
514 * eslEOF: normal end of file
515 *
516 * Throws: <eslEMEM> if a reallocation failed in fgets()
517 *
518 * Xref: STL8 p.56
519 */
520 static int
521 nextline(ESL_FILEPARSER *efp)
522 {
523 int status;
524
525 /* check if we are reading from a file or a buffer */
526 if (efp->is_buffer) {
527 int len;
528 int end;
529 const char *ptr;
530
531 if (efp->mem_pos >= efp->mem_size) return eslEOF;
532
533 len = 0;
534 end = efp->mem_size - efp->mem_pos;
535 ptr = efp->mem_buffer + efp->mem_pos;
536 while (len < end && *ptr++ != '\n') ++len;
537 if (len < end) ++len;
538
539 if (len + 1 > efp->buflen) {
540 ESL_REALLOC(efp->buf, ESL_MAX(64, len * 2));
541 efp->buflen = ESL_MAX(64, len * 2);
542 }
543 memcpy(efp->buf, efp->mem_buffer + efp->mem_pos, len);
544 efp->buf[len] = 0;
545
546 efp->mem_pos += len;
547
548 } else {
549 if ((status = esl_fgets(&(efp->buf), &(efp->buflen), efp->fp)) != eslOK)
550 ESL_FAIL(status, efp->errbuf, "esl_fgets() failed");
551 }
552 efp->s = efp->buf;
553 efp->linenumber++;
554 return eslOK;
555
556 ERROR:
557 return status;
558 }
559
560
561
562 /*****************************************************************
563 * 3. Unit tests.
564 *****************************************************************/
565 #ifdef eslFILEPARSER_TESTDRIVE
566 /* test the interface for getting all tokens in a file, regardless
567 * of newlines. Also, uses the Create/Destroy interface instead of
568 * Open/Close.
569 */
570 static void
571 utest_GetToken(char *filename)
572 {
573 int status;
574 ESL_FILEPARSER *efp = NULL;
575 FILE *fp = NULL;
576 char *tok = NULL;
577 int toklen = 0;
578 int ntok = 0;
579
580 if ((fp = fopen(filename, "r")) == NULL) esl_fatal("File open failed");
581 if ((efp = esl_fileparser_Create(fp)) == NULL) esl_fatal("Failed to associate stream with fileparser");
582 esl_fileparser_SetCommentChar(efp, '#');
583
584 while ((status = esl_fileparser_GetToken(efp, &tok, &toklen)) == eslOK)
585 {
586 if (toklen != 6) esl_fatal("bad token %s", tok);
587 if (strncmp(tok, "token", 5) != 0) esl_fatal("bad token %s", tok);
588 ntok++;
589 }
590 if (status != eslEOF) esl_fatal("Abnormal parse termination");
591 if (ntok != 5) esl_fatal("bad total token number %d\n", ntok);
592
593 esl_fileparser_Destroy(efp);
594 fclose(fp);
595 return;
596 }
597
598 /* test the NextLine and GetTokenOnLine interface, as well as the
599 * Open/Close interface.
600 */
601 static void
602 utest_GetTokenOnLine(char *filename)
603 {
604 int status;
605 ESL_FILEPARSER *efp = NULL;
606 char *tok = NULL;
607 int toklen = 0;
608 int ntok = 0;
609 int nlines = 0;
610 char expect[32];
611
612 if (esl_fileparser_Open(filename, NULL, &efp) != eslOK) esl_fatal("File open failed");
613 esl_fileparser_SetCommentChar(efp, '#');
614
615 while ((status = esl_fileparser_NextLine(efp)) == eslOK)
616 {
617 nlines++;
618 while ((status = esl_fileparser_GetTokenOnLine(efp, &tok, &toklen)) == eslOK)
619 {
620 ntok++;
621 snprintf(expect, 32, "token%d", ntok); // 32 is from the static allocation of expect[32]
622 if (toklen != 6) esl_fatal("bad token length for %s", tok);
623 if (strcmp(expect, tok) != 0) esl_fatal("bad token %s", tok);
624 }
625 if (status != eslEOL) esl_fatal("Unexpected code in place of end-of-line");
626 }
627 if (status != eslEOF) esl_fatal("Unexpected code in place of end-of-file.");
628
629 if (nlines != 3) esl_fatal("expected to parse 3 lines; parsed %d", nlines);
630 if (ntok != 5) esl_fatal("expected to parse 5 tokens; parsed %d", ntok);
631
632 esl_fileparser_Close(efp);
633 return;
634 }
635
636 static void
637 utest_GetTokenBuffered(char *buffer)
638 {
639 int status;
640 ESL_FILEPARSER *efp = NULL;
641 char *tok = NULL;
642 int toklen = 0;
643 int ntok = 0;
644
645 if ((efp = esl_fileparser_CreateMapped(buffer, strlen(buffer))) == NULL)
646 esl_fatal("Failed to associate buffer with fileparser");
647
648 esl_fileparser_SetCommentChar(efp, '#');
649
650 while ((status = esl_fileparser_GetToken(efp, &tok, &toklen)) == eslOK)
651 {
652 if (toklen != 6) esl_fatal("bad token %s", tok);
653 if (strncmp(tok, "token", 5) != 0) esl_fatal("bad token %s", tok);
654 ntok++;
655 }
656 if (status != eslEOF) esl_fatal("Abnormal parse termination");
657 if (ntok != 5) esl_fatal("bad total token number %d\n", ntok);
658
659 esl_fileparser_Destroy(efp);
660
661 return;
662 }
663
664 #endif /*eslFILEPARSER_TESTDRIVE*/
665
666 /*****************************************************************
667 * 4. Test driver.
668 *****************************************************************/
669
670 /*
671 gcc -g -Wall -I. -o test -DeslFILEPARSER_TESTDRIVE esl_fileparser.c easel.c
672 ./test
673 */
674 #ifdef eslFILEPARSER_TESTDRIVE
675 #include <stdio.h>
676 #include <string.h>
677 #include "easel.h"
678 #include "esl_fileparser.h"
679
680 int
681 main(int argc, char **argv)
682 {
683 char tmpfile[32] = "esltmpXXXXXX";
684 FILE *fp;
685
686 char stream[] = "# Full line comment\n"
687 "token1 # Trailing comment\n"
688 "\n" /* blank line */
689 " \n" /* whitespace line */
690 " # sowing comment/whitespace confusion...\n"
691 "token2\ttoken3 token4\n"
692 "token5"; /* file ends w/ no \n */
693
694 /* Create a test file to read.
695 */
696 if (esl_tmpfile_named(tmpfile, &fp) != eslOK) esl_fatal("File open failed");
697 fprintf(fp, "%s", stream);
698 fclose(fp);
699
700 /* Run unit tests using that file.
701 * Unit tests have hardwired knowledge of what's supposed to be in the file.
702 */
703 utest_GetToken(tmpfile);
704 utest_GetTokenOnLine(tmpfile);
705 utest_GetTokenBuffered(stream);
706
707 remove(tmpfile);
708 return 0;
709 }
710 #endif /*eslFILEPARSER_TESTDRIVE*/
711
712
713 /*****************************************************************
714 * 5. Examples.
715 *****************************************************************/
716
717 /* The first example shows the simplest interface: get all tokens
718 * in the file, one at a time.
719 *
720 gcc -g -Wall -I. -o example -DeslFILEPARSER_EXAMPLE esl_fileparser.c easel.c
721 ./example <any file>
722 */
723 #ifdef eslFILEPARSER_EXAMPLE
724 /*::cexcerpt::fileparser_example::begin::*/
725 #include <stdio.h>
726 #include "easel.h"
727 #include "esl_fileparser.h"
728
729 int
730 main(int argc, char **argv)
731 {
732 char *filename = argv[1];
733 int ntok = 1;
734 ESL_FILEPARSER *efp;
735 char *tok;
736 int toklen;
737
738 if (esl_fileparser_Open(filename, NULL, &efp) != eslOK) esl_fatal("File open failed");
739 esl_fileparser_SetCommentChar(efp, '#');
740
741 while (esl_fileparser_GetToken(efp, &tok, &toklen) == eslOK) {
742 printf("%5d %3d %s\n", ntok, toklen, tok);
743 ntok++;
744 }
745 esl_fileparser_Close(efp);
746 return 0;
747 }
748 /*::cexcerpt::fileparser_example::end::*/
749 #endif /*eslFILEPARSER_EXAMPLE*/
750
751 /* The second example shows the more line-oriented interface
752 * of NextLine(), GetTokenOnLine().
753 gcc -g -Wall -I. -o example -DeslFILEPARSER_EXAMPLE2 esl_fileparser.c easel.c
754 ./example <any file>
755 */
756 #ifdef eslFILEPARSER_EXAMPLE2
757 /*::cexcerpt::fileparser_example2::begin::*/
758 #include <stdio.h>
759 #include "easel.h"
760 #include "esl_fileparser.h"
761
762 int
763 main(int argc, char **argv)
764 {
765 char *filename = argv[1];
766 int nline = 1;
767 int ntok;
768 ESL_FILEPARSER *efp;
769 char *tok;
770 int toklen;
771
772 if (esl_fileparser_Open(filename, NULL, &efp) != eslOK) esl_fatal("File open failed");
773 esl_fileparser_SetCommentChar(efp, '#');
774
775 while (esl_fileparser_NextLine(efp) == eslOK)
776 {
777 ntok = 0;
778 while (esl_fileparser_GetTokenOnLine(efp, &tok, &toklen) == eslOK)
779 ntok++;
780 printf("Line %d in the file (%d non-blank, non-comment) contains %d tokens...\n",
781 efp->linenumber, nline, ntok);
782 nline++;
783 }
784 esl_fileparser_Close(efp);
785 return 0;
786 }
787 /*::cexcerpt::fileparser_example2::end::*/
788 #endif /*eslFILEPARSER_EXAMPLE*/
789
790
791