fstat -- Information about Open File

Format

#include <sys\stat.h>
#include <sys\types.h>
int fstat(int handle, struct stat *buffer);

Language Level: XPG4, Extension
fstat obtains information about the open file associated with the given handle and stores it in the structure to which buffer points. The <sys\stat.h> include file defines the stat structure. The stat structure contains the following fields:

Field Value
st_mode Bit mask for file mode information. fstat sets the S_IFCHR bit if handle refers to a device. The S_IFDIR bit is set if pathname specifies a directory. It sets the S_IFREG bit if handle refers to an ordinary file. It sets user read/write bits according to the permission mode of the file. The other bits have undefined values.

st_dev Drive number of the disk containing the file.
st_rdev Drive number of the disk containing the file (same as st_dev).
st_nlink Always 1.
st_size Size of the file in bytes.
st_atime Time of last access of file.
st_mtime Time of last modification of file.
st_ctime Time of file creation.

There are three additional fields in the stat structure for portability to other operating systems; they have no meaning under the OS/2 or Windows operating systems.

Note:

  1. If the given handle refers to a device, the size and time fields in the stat structure are not meaningful.
  2. In earlier releases of the C/C++ run-time library, fstat began with an underscore (_fstat). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, IBM C and C++ Compilers will map _fstat to fstat for you.

Return Value
If it obtains the file status information, fstat returns 0. A return value of -1 indicates an error, and fstat sets errno to EBADF, showing an incorrect file handle.

Example
This example uses fstat to report the size of a file named data.

#include <time.h>
#include <sys\types.h>
#include <sys\stat.h>
#include <stdio.h>
int main(void)
{
   struct stat buf;
   FILE *fp;
   int fh,result;
   char *buffer = "A line to output";
   fp = fopen("data", "w+");
   fprintf(fp, "%s", buffer);
   fflush(fp);
   fclose(fp);
   fp = fopen("data", "r");
   if (0 == fstat(fileno(fp), &buf)) {
      printf("file size is %ld\n", buf.st_size);
      printf("time modified is %s\n", ctime(&buf.st_atime));
   }
   else
      printf("Bad file handle\n");
   fclose(fp);
   return 0;
   /*********************************************************
      The output should be similar to:
      file size is 16
      time modified is Thu May 16 16:08:14 1995
   *********************************************************/
}


stat -- Get Information about File or Directory
<sys\stat.h>
<sys\types.h>