Last active
August 29, 2015 14:11
-
-
Save alcarney/aae3b583a956d92861b1 to your computer and use it in GitHub Desktop.
A simple C program to count all the lines in a file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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