fstat, stat, _wstat
Go Up to sys\stat.h Index
Header File
sys\stat.h
Category
Input/output Routines
Prototype
int fstat(int handle, struct stat *statbuf);
int stat(const char *path, struct stat *statbuf);
int _wstat(const wchar_t *path, struct _stat *statbuf);
Description
Gets open file information.
fstat stores information in the stat structure about the file or directory associated with handle.
stat stores information about a given file or directory in the stat/_stat structure. The name of the file is path.
statbuf points to the stat/_stat structure (defined in sys\stat.h). That structure contains the following fields:
st_mode |
Bit mask giving information about the file's mode |
st_dev |
Drive number of disk containing the file or file handle if the file is on a device |
st_rdev |
Same as st_dev |
st_nlink |
Set to the integer constant 1 |
st_size |
Size of the file in bytes |
st_atime |
Most recent access (Windows) or last time modified (DOS) |
st_mtime |
Same as st_atime |
st_ctime |
Same as st_atime |
The stat structure contains three more fields not mentioned here. They contain values that are meaningful only in UNIX.
The st_mode bit mask that gives information about the mode of the open file includes the following bits:
One of the following bits will be set:
S_IFCHR |
If handle refers to a device. |
S_IFREG |
If an ordinary file is referred to by handle. |
One or both of the following bits will be set:
S_IWRITE |
If user has permission to write to file. |
S_IREAD |
If user has permission to read to file. |
The HPFS and NTFS file-management systems make the following distinctions:
st_atime |
Most recent access |
st_mtime |
Most recent modify |
st_ctime |
Creation time |
Return Value
fstat and stat return 0 if they successfully retrieved the information about the open file.
On error (failure to get the information) these functions return -1 and set the global variable errno to
EBADF |
Bad file handle |
Example
#include <sys\stat.h> #include <stdio.h> #include <time.h> int main(void) { struct stat statbuf; FILE *stream; /* open a file for update */ if ((stream = fopen("DUMMY.FIL", "w+")) == NULL) { fprintf(stderr, "Cannot open output file.\n"); return(1); } fprintf(stream, "This is a test"); fflush(stream); /* get information about the file */ fstat(fileno(stream), &statbuf); fclose(stream); /* display the information returned */ if (statbuf.st_mode & S_IFCHR) printf("Handle refers to a device.\n"); if (statbuf.st_mode & S_IFREG) printf("Handle refers to an ordinary file.\n"); if (statbuf.st_mode & S_IREAD) printf("User has read permission on file.\n"); if (statbuf.st_mode & S_IWRITE) printf("User has write permission on file.\n"); printf("Drive letter of file: %c\n", 'A'+statbuf.st_dev); printf("Size of file in bytes: %ld\n", statbuf.st_size); printf("Time file last opened: %s\n", ctime(&statbuf.st_ctime)); return 0; }