bmalhi bmalhi - 1 year ago 48
Linux Question

To count the total number of lines in a file using Unix system call in C

I am a beginner in C language and unix do not have much experience in it. I am trying to count total lines inside the file using unix system call but I am getting no result. My lineCount is always coming out as 0 I do not know why? I want someone to help me figure out the line count if possible.Thanks

int lineCount = 0;
while (*buffer != '\0') // to check the end of the file
read( in_fd, buffer, BUFFERSZ);
if (*buffer == '\n')

printf("Linecount: %i \n", lineCount );

Answer Source

Your code only checks *buffer for newlines, which is the first character of each BUFFERSZ chunk you read, i.e. your code doesn't even look at most of the input. (It also doesn't check for end-of-file correctly: you need to look at read's return value for that.)

Here's a simple solution that emulates fgetc using read:

size_t lines = 0;
char c;
while (read(in_fd, &c, 1) == 1) {
    if (c == '\n') {

printf("Linecount: %zu\n", lines);

If you can't use printf either, a quick workaround is:

static void print_n(size_t n) {
    if (n / 10) {
        print_n(n / 10);
    char c = '0' + n % 10;
    write(1, &c, 1);

write(1, "Linecount: ", strlen("Linecount: "));
write(1, "\n", 1);