aboutsummaryrefslogtreecommitdiff
path: root/libbb
diff options
context:
space:
mode:
Diffstat (limited to 'libbb')
-rw-r--r--libbb/get_line_from_file.c70
1 files changed, 70 insertions, 0 deletions
diff --git a/libbb/get_line_from_file.c b/libbb/get_line_from_file.c
index 3a76f49a0..7b65ced8d 100644
--- a/libbb/get_line_from_file.c
+++ b/libbb/get_line_from_file.c
@@ -67,3 +67,73 @@ char* FAST_FUNC xmalloc_fgetline(FILE *file)
return c;
}
+
+/* Faster routines (~twice as fast). +170 bytes. Unused as of 2008-07.
+ *
+ * NB: they stop at NUL byte too.
+ * Performance is important here. Think "grep 50gigabyte_file"...
+ * Iironically, grep can't use it because of NUL issue.
+ * We sorely need C lib to provide fgets which reports size!
+ */
+
+static char* xmalloc_fgets_internal(FILE *file, int *sizep)
+{
+ int len;
+ int idx = 0;
+ char *linebuf = NULL;
+
+ while (1) {
+ char *r;
+
+ linebuf = xrealloc(linebuf, idx + 0x100);
+ r = fgets(&linebuf[idx], 0x100, file);
+ if (!r) {
+ /* need to terminate in case this is error
+ * (EOF puts NUL itself) */
+ linebuf[idx] = '\0';
+ break;
+ }
+ /* stupid. fgets knows the len, it should report it somehow */
+ len = strlen(&linebuf[idx]);
+ idx += len;
+ if (len != 0xff || linebuf[idx - 1] == '\n')
+ break;
+ }
+ *sizep = idx;
+ if (idx) {
+ /* xrealloc(linebuf, idx + 1) is up to caller */
+ return linebuf;
+ }
+ free(linebuf);
+ return NULL;
+}
+
+/* Get line, remove trailing \n */
+char* FAST_FUNC xmalloc_fgetline_fast(FILE *file)
+{
+ int sz;
+ char *r = xmalloc_fgets_internal(file, &sz);
+ if (r && r[sz - 1] == '\n')
+ r[--sz] = '\0';
+ return r; /* not xrealloc(r, sz + 1)! */
+}
+
+#if 0
+char* FAST_FUNC xmalloc_fgets(FILE *file)
+{
+ int sz;
+ return xmalloc_fgets_internal(file, &sz);
+}
+
+/* Get line, remove trailing \n */
+char* FAST_FUNC xmalloc_fgetline(FILE *file)
+{
+ int sz;
+ char *r = xmalloc_fgets_internal(file, &sz);
+ if (!r)
+ return r;
+ if (r[sz - 1] == '\n')
+ r[--sz] = '\0';
+ return xrealloc(r, sz + 1);
+}
+#endif