Next: , Previous: , Up: FAQ   [Contents][Index]


How do I track the byte offset for lseek()?

>   We thought that it would be possible to have this number through the
>   evaluation of the following expression:
>
>   seek_position = (no_buffers)*YY_READ_BUF_SIZE + yy_c_buf_p - YY_CURRENT_BUFFER->yy_ch_buf

While this is the right idea, it has two problems. The first is that it’s possible that flex will request less than YY_READ_BUF_SIZE during an invocation of YY_INPUT (or that your input source will return less even though YY_READ_BUF_SIZE bytes were requested). The second problem is that when refilling its internal buffer, flex keeps some characters from the previous buffer (because usually it’s in the middle of a match, and needs those characters to construct yytext for the match once it’s done). Because of this, yy_c_buf_p - YY_CURRENT_BUFFER->yy_ch_buf won’t be exactly the number of characters already read from the current buffer.

An alternative solution is to count the number of characters you’ve matched since starting to scan. This can be done by using YY_USER_ACTION. For example,

#define YY_USER_ACTION num_chars += yyleng;

(You need to be careful to update your bookkeeping if you use yymore(), yyless(), unput(), or input().)