summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJari Vetoniemi <mailroxas@gmail.com>2014-04-12 19:21:40 +0300
committerJari Vetoniemi <mailroxas@gmail.com>2014-04-12 19:21:40 +0300
commitcd73a1ba610db7cfa928b37039a1bbdaee88972a (patch)
tree82bf385739da6f27334f4d6594823b57e1025dbb
parent042448798d9d2b95ce5ab9ce718b9a16ef0a5fc1 (diff)
downloadbemenu-cd73a1ba610db7cfa928b37039a1bbdaee88972a.tar.gz
bemenu-cd73a1ba610db7cfa928b37039a1bbdaee88972a.tar.bz2
bemenu-cd73a1ba610db7cfa928b37039a1bbdaee88972a.zip
Read items from stdin nicer (assumes stdin can fit on one buffer)
-rw-r--r--client/client.c79
1 files changed, 18 insertions, 61 deletions
diff --git a/client/client.c b/client/client.c
index 130d972..c031c0b 100644
--- a/client/client.c
+++ b/client/client.c
@@ -5,80 +5,37 @@
#include <assert.h>
#include <bemenu.h>
-static ptrdiff_t getLine(char **outLine, size_t *outAllocated, FILE *stream)
+static void readItemsToMenuFromStdin(bmMenu *menu)
{
- size_t len = 0, allocated;
- char *s, *buffer;
-
- assert(outLine);
- assert(outAllocated);
-
- if (!stream || feof(stream) || ferror(stream))
- return -1;
+ assert(menu);
- allocated = *outAllocated;
- buffer = *outLine;
+ size_t step = 1024, allocated;
+ char *buffer;
- if (!buffer || allocated == 0) {
- if (!(buffer = calloc(1, (allocated = 1024) + 1)))
- return -1;
- }
+ if (!(buffer = malloc((allocated = step))))
+ return;
- for (s = buffer;;) {
- if (!fgets(s, allocated - (s - buffer), stream)) {
- *outAllocated = allocated;
- *outLine = buffer;
- return -1;
- }
-
- len = strlen(s);
- if (feof(stream))
- break;
-
- if (len > 0 && s[len - 1] == '\n')
- break;
-
- if (len + 1 >= allocated - (s - buffer)) {
- void *tmp = realloc(buffer, 2 * allocated);
- if (!tmp)
- break;
-
- buffer = tmp;
- s = buffer + allocated - 1;
- memset(s, 0, allocated - (s - buffer));
- allocated *= 2;
- } else {
- s += len;
+ size_t read;
+ while ((read = fread(buffer + (allocated - step), 1, step, stdin)) == step) {
+ void *tmp;
+ if (!(tmp = realloc(buffer, (allocated += step)))) {
+ free(buffer);
+ return;
}
+ buffer = tmp;
}
+ buffer[allocated - step + read - 1] = 0;
- *outAllocated = allocated;
- *outLine = buffer;
-
- if (s[len - 1] == '\n')
- s[len - 1] = 0;
-
- return s - buffer + len;
-}
-
-static void readItemsToMenuFromStdin(bmMenu *menu)
-{
- assert(menu);
-
- ptrdiff_t len;
- size_t size = 0;
- char *line = NULL;
-
- while ((len = getLine(&line, &size, stdin)) != -1) {
- bmItem *item = bmItemNew((len > 0 ? line : NULL));
+ char *s;
+ for (s = strtok(buffer, "\n"); s; s = strtok(NULL, "\n")) {
+ bmItem *item = bmItemNew(s);
if (!item)
break;
bmMenuAddItem(menu, item);
}
- if (line)
- free(line);
+ free(buffer);
}
int main(int argc, char **argv)