1 /*-------------------------------------------------------------------------
3 * src/port/pgcheckdir.c
5 * A simple subroutine to check whether a directory exists and is empty or not.
6 * Useful in both initdb and the backend.
8 * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
9 * Portions Copyright (c) 1994, Regents of the University of California
11 *-------------------------------------------------------------------------
20 * Test to see if a directory exists and is empty or not.
24 * 1 if exists and empty
25 * 2 if exists and contains _only_ dot files
26 * 3 if exists and contains a mount point
27 * 4 if exists and not empty
28 * -1 if trouble accessing directory (errno reflects the error)
31 pg_check_dir(const char *dir)
36 bool dot_found = false;
37 bool mount_found = false;
40 chkdir = opendir(dir);
42 return (errno == ENOENT) ? 0 : -1;
44 while (errno = 0, (file = readdir(chkdir)) != NULL)
46 if (strcmp(".", file->d_name) == 0 ||
47 strcmp("..", file->d_name) == 0)
49 /* skip this and parent directory */
53 /* file starts with "." */
54 else if (file->d_name[0] == '.')
58 /* lost+found directory */
59 else if (strcmp("lost+found", file->d_name) == 0)
66 result = 4; /* not empty */
72 result = -1; /* some kind of I/O error? */
74 /* Close chkdir and avoid overwriting the readdir errno on success */
75 readdir_errno = errno;
77 result = -1; /* error executing closedir */
79 errno = readdir_errno;
81 /* We report on mount point if we find a lost+found directory */
82 if (result == 1 && mount_found)
85 /* We report on dot-files if we _only_ find dot files */
86 if (result == 1 && dot_found)