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


USACO Section 1.1 Broken Necklace

Sat 30 November 2013

Let's describe the problem briefly here. Given a string a necklace composed with Red, Blue and White beans, we are going to find the maximum number of beans we can collected if we can choose to break the necklace at a certain point. By "maximum number of beans we can collected", I mean starting from the break point, we collect beads of the same color from one end until you reach a bead of a different color, and do the same for the other end.

Category: Algorithm Tagged: C USACO Algorithm

comments

Read More
Page 1 of 2

Next »