Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use fgets() to avoid casting its second argument which is of type int?

Tags:

The declaration of the fgets function look like this:

char *fgets(char *str, int n, FILE *stream);

This means that the second argument is expected to be an int.

Which is the proper way to avoid this casting in the following program?

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

int main(void) {
    const char *buffer = "Michi";
    size_t len = strlen(buffer) + 1;
    char arr[len];

    printf("Type your Input:> ");
    if (fgets(arr, (int)len, stdin) == NULL) {
        printf("Error, fgets\n");
        exit(1);
    } else {
        printf("Arr = %s\n", arr);
    }
}

Here I used (int)len which looks fine, but what happens if buffer stores a very long string?

Lets say:

const char *buffer = "Very long long ..."; /* where length is beyond the range of the `int` type */

I already declared length of the type size_t which is fine here, but if I'll pass it to fgets is not OK because of:

conversion to ‘int’ from ‘size_t {aka long unsigned int}’ may alter its value

and if I cast it to int won't fit because the size of the int is smaller than the size of length and some information will be lost.

Maybe I'm missing something here...

Any way how should I avoid this situation?