Skip to content

Instantly share code, notes, and snippets.

@willb
Forked from mattf/gist:163524
Created August 6, 2009 21:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willb/163571 to your computer and use it in GitHub Desktop.
Save willb/163571 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <deque>
#define MAX_LINE_LEN 1024
struct Poller
{
typedef std::deque<char *> LinesType;
typedef LinesType::const_iterator LinesTypeIterator;
typedef std::pair<LinesTypeIterator, LinesTypeIterator> LinesTypeIterators;
LinesType lines;
~Poller()
{
for (LinesType::iterator i = lines.begin();
i != lines.end();
i++) {
free(*i);
}
}
LinesTypeIterators
poll(FILE *f)
{
int size = lines.size();
char buf[MAX_LINE_LEN];
while (true) {
if (NULL == fgets(buf, MAX_LINE_LEN, f)) break;
lines.push_back(strdup(buf));
}
return LinesTypeIterators(lines.begin() + size, lines.end());
}
};
int
main(int argc, char **argv)
{
FILE *f = fopen(argv[1], "r");
if (!f) return 1;
Poller poller;
for (int c = 0; c < 10; c++) {
Poller::LinesTypeIterators ij = poller.poll(f);
for (Poller::LinesTypeIterator i = ij.first;
i != ij.second;
i++) {
printf("%s", *i);
}
sleep(1);
}
printf("All lines:\n");
for (Poller::LinesType::iterator i = poller.lines.begin();
i != poller.lines.end();
i++) {
printf("%s", *i);
}
fclose(f);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment