gtpc2m2lC/C++ Language Support User's Guide

fileno-Get the File Descriptor from an Open Stream

This function returns the file descriptor number associated with a specified stream.

Format

#define _POSIX_SOURCE
#include <stdio.h>
int fileno(const FILE *stream);

stream
The stream for which the associated file descriptor will be returned.

The argument stream points to a FILE structure controlling a stream.

The unistd.h header file defines the following macros, which are constants that map to the file descriptors of the standard streams:

STDIN_FILENO
Standard input, stdin (value 0).

STDOUT_FILENO
Standard output, stdout (value 1).

STDERR_FILENO
Standard error, stderr (value 2).
Note:
stdin, stdout, and stderr are macros, not constants.

Normal Return

If successful, the fileno function returns the file descriptor number associated with an open stream (that is, one opened with the fopen, fdopen, or freopen functions).

Error Return

If unsuccessful, fileno returns -1 and sets errno to EBADF, which indicates one of the following:

Programming Considerations

None.

Examples

The following example shows one use of the fileno function.

#define _POSIX_SOURCE
#include <errno.h>
#include <stdio.h>
 
main() {
  FILE *stream;
  char my_file[]="my.file";
 
  printf("fileno(stdin) = %d\n", fileno(stdin));
 
  if ((stream = fopen(my_file, "w")) == NULL)
    perror("fopen() error");
  else {
    printf("fileno() of the file is %d\n", fileno(stream));
    fclose(stream);
    remove(my_file);
  }
}

Output

fileno(stdin) = 0
fileno() of the file is 3

Related Information

See Appendix E, Programming Support for the TPF File System for more information about TPF File System C Functions.