/* * stattest — exercise POSIX stat() and fstat() over ESTEX file metadata. * * Calls: * stat() on a file by path * stat() on a directory (current dir) * stat() on a non-existent file (expects errno=ENOENT) * fstat() on a freshly opened file */ #include #include #include #include #include #include #include static const char *mode_str(uint16_t m) { if (S_ISDIR(m)) return "DIR"; if (S_ISREG(m)) return "REG"; return "???"; } static void print_stat(const char *what, const struct stat *st) { char buf[32]; /* Reuse asctime by converting epoch → struct tm. */ time_t t = st->st_mtime; struct tm *tm = localtime(&t); sprintf(buf, "%04d-%02d-%02d %02d:%02d:%02d", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec); printf(" %s: mode=%s perm=0%o size=%lu mtime=%s\n", what, mode_str(st->st_mode), (unsigned)(st->st_mode & 0777), (unsigned long)st->st_size, buf); } int main(int argc, char **argv) { struct stat st; puts("stattest: stat() / fstat() smoke test"); /* stat on this very file (the .exe). */ if (stat(argv[0], &st) == 0) print_stat("self.exe", &st); else printf(" stat(\"%s\") failed: errno=%d (%s)\n", argv[0], errno, strerror(errno)); /* stat on a definitely-missing file. */ errno = 0; if (stat("NOSUCH.XXX", &st) == 0) puts(" stat(NOSUCH.XXX) unexpectedly succeeded?!"); else printf(" stat(NOSUCH.XXX) -> errno=%d (%s) [expected ENOENT]\n", errno, strerror(errno)); /* fstat on a fresh handle (open the running exe read-only). */ int fd = open(argv[0], O_RDONLY); if (fd < 0) { printf(" open(\"%s\") failed: errno=%d (%s)\n", argv[0], errno, strerror(errno)); } else { if (fstat(fd, &st) == 0) print_stat("fstat(self)", &st); else printf(" fstat failed: errno=%d (%s)\n", errno, strerror(errno)); close(fd); } /* Extra argv-passed path. */ if (argc > 1) { if (stat(argv[1], &st) == 0) print_stat(argv[1], &st); else printf(" stat(\"%s\") failed: errno=%d (%s)\n", argv[1], errno, strerror(errno)); } return 0; }