Check file exist for given path string

I want to check if the file (or directory) is really exist at given path (string like path/to/file). Found this method:

Is it correct choice for these needs?

I find it usually better to just open the file in question and handle the failing of that if it doesn’t exist. What is your use-case?

1 Like

I need just parse some string from browser Entry input (by using lookup method), then handle it as the file, or just make search request to provider. In my case, there is no needs to open it before the route to handler.

How about g_file_new_for_path then g_file_query_exists?

1 Like

Thanks, but g_file_new_for_path always return File object and g_file_query_exists requires available File object, when I’m operating with the string input.

+1, this is the method I personally use.

Recently using std method.

1 Like

As Jens says, opening the file and handling errors from that is the only safe way to do things.

Any approach which involves checking whether the file exists (using g_file_query_exists() or similar) will be subject to a time-of-check to time-of-use race. You will have to handle the possibility of a G_IO_ERROR_NOT_FOUND error from subsequent file read/write operations on the file anyway, regardless of the return value of g_file_query_exists(). This is because another process could modify/delete/create the file between you process calling g_file_query_exists() and your process subsequently opening the file. The file system is a shared, global resource.

3 Likes

opening the file and handling errors from that is the only safe way to do things.

This is documented in detail in Gio.File.query_exists.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.