Get the file number associated with a FILE pointer

This example C program demonstrates how to get the file number from a FILE *.

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

int main ()
{
    FILE * f;
    int file_number;
    char * file_name;
    file_name = "gfn.c";
    f = fopen (file_name, "r");
    if (! f) {
	fprintf (stderr, "%s could not be opened: %s\n",
		 file_name, strerror (errno));
	return -1;
    }
    file_number = fileno (f);
    printf ("The file %s has number %d.\n", file_name, file_number);
    fclose (f);
    return 0;
}

(download)

The output of the example looks like this:

The file gfn.c has number 3.


Copyright © Ben Bullock 2009-2017. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com). / Privacy / Disclaimer