Skip to content

Instantly share code, notes, and snippets.

@alcarney
Last active August 29, 2015 14:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alcarney/aae3b583a956d92861b1 to your computer and use it in GitHub Desktop.
Save alcarney/aae3b583a956d92861b1 to your computer and use it in GitHub Desktop.
A simple C program to count all the lines in a file
#include <stdio.h>
#include <stdbool.h>
int main(int argc, char* argv[])
{
// Check that enough arguments were given
if(argc != 2)
{
fprintf(stderr, "Usage:\n\tcount_lines <filename>\n");
return 1;
}
// Try and open the file
FILE* fp;
if (!(fp = fopen(argv[1], "r")))
{
fprintf(stderr, "Unable to open file %s\n", argv[1]);
return 1;
}
// Initialise some variables
const unsigned int buffer_length = 4096;
char buffer[buffer_length];
unsigned int num_lines = 0;
// Loop through the file
while (true)
{
// Get the next line
fgets(buffer, buffer_length, fp);
// Check if we reached the end of the file
if(feof(fp))
break;
// Increment the line counter
num_lines++;
}
// Close the file
fclose(fp);
// How many lines was that?
printf("The file %s contains %u lines\n", argv[1], num_lines);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment