1e533127050fedbcfc20ba2ea816d2eda0514949
[reactos.git] / reactos / lib / crt / sys_stat / fstat.c
1 /* $Id$
2 *
3 * COPYRIGHT: See COPYING in the top level directory
4 * PROJECT: ReactOS system libraries
5 * FILE: lib/msvcrt/sys/fstat.c
6 * PURPOSE: Gather file information
7 * PROGRAMER: Boudewijn Dekker
8 * UPDATE HISTORY:
9 * 28/12/98: Created
10 */
11
12 #include "precomp.h"
13 #include <sys/types.h>
14 #include <sys/stat.h>
15 #include <fcntl.h>
16 #include <string.h>
17 #include <errno.h>
18 #include <internal/file.h>
19
20
21 /*
22 * @implemented
23 */
24 int _fstat(int fd, struct _stat* statbuf)
25 {
26 BY_HANDLE_FILE_INFORMATION FileInformation;
27 DWORD dwFileType;
28 void* handle;
29
30 if (!statbuf) {
31 __set_errno(EINVAL);
32 return -1;
33 }
34
35 if ((void*)-1 == (handle = (void*)_get_osfhandle(fd)))
36 {
37 __set_errno(EBADF);
38 return -1;
39 }
40
41 fflush(NULL);
42
43 memset (statbuf, 0, sizeof(struct stat));
44
45 dwFileType = GetFileType(handle);
46
47 if (dwFileType == FILE_TYPE_DISK)
48 {
49 if (!GetFileInformationByHandle(handle,&FileInformation))
50 {
51 __set_errno(EBADF);
52 return -1;
53 }
54 statbuf->st_ctime = FileTimeToUnixTime(&FileInformation.ftCreationTime,NULL);
55 statbuf->st_atime = FileTimeToUnixTime(&FileInformation.ftLastAccessTime,NULL);
56 statbuf->st_mtime = FileTimeToUnixTime(&FileInformation.ftLastWriteTime,NULL);
57
58 statbuf->st_dev = fd;
59 statbuf->st_size = FileInformation.nFileSizeLow;
60 statbuf->st_mode = S_IREAD;
61 if (FileInformation.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
62 statbuf->st_mode |= S_IFDIR;
63 else
64 statbuf->st_mode |= S_IFREG;
65 if (!(FileInformation.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
66 statbuf->st_mode |= S_IWRITE;
67 }
68 else if (dwFileType == FILE_TYPE_CHAR)
69 {
70 statbuf->st_dev = fd;
71 statbuf->st_mode = S_IFCHR;
72 }
73 else if (dwFileType == FILE_TYPE_PIPE)
74 {
75 statbuf->st_dev = fd;
76 statbuf->st_mode = S_IFIFO;
77 }
78 else
79 {
80 // dwFileType is FILE_TYPE_UNKNOWN or has a bad value
81 __set_errno(EBADF);
82 return -1;
83 }
84 return 0;
85 }