Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a file can be written using C++

Tags:

c++

file

boost

In C++ how can I determine if the program has either read-only access or read-write access to a file? I searched the boost filesystem library but I have yet to find something to help me. Right now I thinking of opening the file, trying to write inside and check for error, but that doesn't seem a very appropriate way of doing this.

Any clue?

EDIT : it would need to be cross platform

like image 620
Laurent Bourgault-Roy Avatar asked Oct 22 '25 16:10

Laurent Bourgault-Roy


2 Answers

At the end of the day, the only way to test if you can write data to a file on a modern OS is to actually try to write it. Lots of things could have happened to the file between tests for permission and the actual write.

The system call, which most runtime libraries fully support, is

#include <unistd.h>

if (0 == access (char *pathname, int mode))
    // permission is granted

where mode is F_OK to test existence of file, or a mask consisting of the bitwise OR of one or more of R_OK, W_OK, and X_OK.

like image 36
wallyk Avatar answered Oct 25 '25 05:10

wallyk