Skip to content

Instantly share code, notes, and snippets.

@mpontillo
Created December 29, 2012 09:44
Show Gist options
  • Save mpontillo/4405788 to your computer and use it in GitHub Desktop.
Save mpontillo/4405788 to your computer and use it in GitHub Desktop.
Simple line count program using POSIX file APIs.
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
void count_lines(char* filename)
{
int fd;
int s;
int i;
int lines = 0;
static char buf[32768];
fd = open(filename, O_RDONLY);
if(0 > fd)
{
perror(filename);
return;
}
while(0 < (s = read(fd, &buf, sizeof(buf))))
{
for(i = 0 ; i < s ; i++)
{
if(buf[i] == '\n') lines++;
}
}
close(fd);
printf("%8d %s\n", lines, filename);
}
int main(int argc, char* argv[])
{
int i = 1;
if(argc < 2)
{
return 1;
}
for(; i < argc ; i++)
{
count_lines(argv[i]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment