+static void grep_file(FILE *file)
+{
+ char *line = NULL;
+ int ret;
+ int linenum = 0;
+ int nmatches = 0;
+ int i;
+#ifdef BB_FEATURE_GREP_CONTEXT
+ int print_n_lines_after = 0;
+ int curpos = 0; /* track where we are in the circular 'before' buffer */
+ int idx = 0; /* used for iteration through the circular buffer */
+#endif /* BB_FEATURE_GREP_CONTEXT */
+
+ while ((line = get_line_from_file(file)) != NULL) {
+ chomp(line);
+ linenum++;
+
+ for (i = 0; i < nregexes; i++) {
+ /*
+ * test for a postitive-assertion match (regexec returns success (0)
+ * and the user did not specify invert search), or a negative-assertion
+ * match (regexec returns failure (REG_NOMATCH) and the user specified
+ * invert search)
+ */
+ ret = regexec(®exes[i], line, 0, NULL, 0);
+ if ((ret == 0 && !invert_search) || (ret == REG_NOMATCH && invert_search)) {
+
+ /* if we found a match but were told to be quiet, stop here and
+ * return success */
+ if (be_quiet)
+ exit(0);
+
+ /* keep track of matches */
+ nmatches++;
+
+ /* if we're just printing filenames, we stop after the first match */
+ if (print_files_with_matches)
+ break;
+
+ /* print the matched line */
+ if (print_match_counts == 0) {
+#ifdef BB_FEATURE_GREP_CONTEXT
+ int prevpos = (curpos == 0) ? lines_before - 1 : curpos - 1;
+
+ /* if we were told to print 'before' lines and there is at least
+ * one line in the circular buffer, print them */
+ if (lines_before && before_buf[prevpos] != NULL) {
+ int first_buf_entry_line_num = linenum - lines_before;
+
+ /* advance to the first entry in the circular buffer, and
+ * figure out the line number is of the first line in the
+ * buffer */
+ idx = curpos;
+ while (before_buf[idx] == NULL) {
+ idx = (idx + 1) % lines_before;
+ first_buf_entry_line_num++;
+ }
+
+ /* now print each line in the buffer, clearing them as we go */
+ while (before_buf[idx] != NULL) {
+ print_line(before_buf[idx], first_buf_entry_line_num, '-');
+ free(before_buf[idx]);
+ before_buf[idx] = NULL;
+ idx = (idx + 1) % lines_before;
+ first_buf_entry_line_num++;
+ }
+ }
+
+ /* make a note that we need to print 'after' lines */
+ print_n_lines_after = lines_after;
+#endif /* BB_FEATURE_GREP_CONTEXT */
+ print_line(line, linenum, ':');
+ }
+ }
+#ifdef BB_FEATURE_GREP_CONTEXT
+ else { /* no match */
+ /* Add the line to the circular 'before' buffer */
+ if(lines_before) {
+ if(before_buf[curpos])
+ free(before_buf[curpos]);
+ before_buf[curpos] = strdup(line);
+ curpos = (curpos + 1) % lines_before;
+ }
+ }