Function

GLibfile_test

Declaration

gboolean
g_file_test (
  const gchar* filename,
  GFileTest test
)

Description

Returns TRUE if any of the tests in the bitfield test are TRUE. For example, (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) will return TRUE if the file exists; the check whether it’s a directory doesn’t matter since the existence test is TRUE. With the current set of available tests, there’s no point passing in more than one test at a time.

Apart from G_FILE_TEST_IS_SYMLINK all tests follow symbolic links, so for a symbolic link to a regular file g_file_test() will return TRUE for both G_FILE_TEST_IS_SYMLINK and G_FILE_TEST_IS_REGULAR.

Note, that for a dangling symbolic link g_file_test() will return TRUE for G_FILE_TEST_IS_SYMLINK and FALSE for all other flags.

You should never use g_file_test() to test whether it is safe to perform an operation, because there is always the possibility of the condition changing before you actually perform the operation, see TOCTOU.

For example, you might think you could use G_FILE_TEST_IS_SYMLINK to know whether it is safe to write to a file without being tricked into writing into a different location. It doesn’t work!

 // DON'T DO THIS
 if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK))
   {
     fd = g_open (filename, O_WRONLY);
     // write to fd
   }

 // DO THIS INSTEAD
 fd = g_open (filename, O_WRONLY | O_NOFOLLOW | O_CLOEXEC);
 if (fd == -1)
   {
     // check error
     if (errno == ELOOP)
       // file is a symlink and can be ignored
     else
       // handle errors as before
   }
 else
   {
     // write to fd
   }

Another thing to note is that G_FILE_TEST_EXISTS and G_FILE_TEST_IS_EXECUTABLE are implemented using the access() system call. This usually doesn’t matter, but if your program is setuid or setgid it means that these tests will give you the answer for the real user ID and group ID, rather than the effective user ID and group ID.

On Windows, there are no symlinks, so testing for G_FILE_TEST_IS_SYMLINK will always return FALSE. Testing for G_FILE_TEST_IS_EXECUTABLE will just check that the file exists and its name indicates that it is executable, checking for well-known extensions and those listed in the PATHEXT environment variable.

Parameters

filename

Type: const gchar*

A filename to test in the GLib file name encoding.

The data is owned by the caller of the function.
The value is a file system path, using the OS encoding.
test

Type: GFileTest

Bitfield of GFileTest flags.

Return value

Type: gboolean

Whether a test was TRUE.