fgets: How Many Characters/Bytes Are Read?

Sat 15 February 2014

If you have ever used fgets, you probably know we check its return value to know if the reading is done, by comparing the return value with NULL.

But apparently fgets itself doesn't tell you how many characters or bytes are read every time you call it.

To do this, we will need ftell. Every time after you called fgets to read from a "FILE", the position indicator of the "FILE" stream is moved to the position next to the end of what you have read, i.e. the beginning of the rest of the stream. ftell simply returns the current value of the position indicator of the "FILE" stream, so by comparing the positions you get before and after a fgets call, you will be able to know how many characters or bytes are just read.

Test it:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFF_SIZE 1024

int main()
{
    FILE* bs_fp = NULL;
    char buff[BUFF_SIZE] = {0};
    int last_pos = 0;
    int curr_pos = 0;

    bs_fp = fopen("test.txt", "r");

    if(!bs_fp)
    {
        goto exit;
    }

    while(fgets(buff, BUFF_SIZE, bs_fp) != NULL)
    {

        curr_pos = ftell(bs_fp);
        printf("read size = %d\n",curr_pos - last_pos);
        last_pos = curr_pos;
    }

exit:
    if(bs_fp)
        fclose(bs_fp);

    return 0;
}

Category: C Language Tagged: C

Comments