/* read_lines.cpp
*/
#include <stdio.h>
#include <string>
#include <vector>
int main(int argc, char *argv[])
{
if (argc < 2)
{
fprintf(stderr, "Usage: read_lines filename\n");
return 1;
}
FILE *fp = fopen(argv[1], "r");
if (!fp)
{
fprintf(stderr, "Failed to open %s\n", argv[1]);
return 2;
}
typedef std::vector< std::string > lines_t;
lines_t lines;
const size_t buffer_size = 1024;
char *buffer = new char[buffer_size];
std::string residue;
while (!feof(fp) && !ferror(fp))
{
size_t bytes_read = fread(buffer, 1, buffer_size, fp);
const char *buffer_end = buffer + bytes_read;
const char *b = buffer;
const char *e;
while((e = (const char *)memchr(b, '\n', buffer_end - b)) != NULL)
{
std::string line(b, e);
residue += line;
lines.push_back(residue);
residue.clear();
b = e + 1;
}
// Is there any residue?
if (b < buffer_end)
{
// There's some residue
residue += std::string(b, buffer_end);
}
}
if (!residue.empty())
lines.push_back(residue);
delete [] buffer;
fclose(fp);
int n = 0;
for (lines_t::const_iterator i = lines.begin(); i != lines.end(); ++i)
{
++n;
printf("%d: %s\n", n, i->c_str());
}
return 0;
}