How can I check if I have read or write access to a directory?
38 views (last 30 days)
Show older comments
MathWorks Support Team
on 21 Jul 2016
Commented: Walter Roberson
on 25 Aug 2020
When I do
>> fileattrib('\\path\to\my\folder')
"UserRead" and "UserWrite" is "1" even though Windows Explorer shows that I do not have read or write access in the folder properties. Furthermore, when I try to read or write in the directory, it fails. Why does "fileattrib" indicate that I have read and write access even though I do not?
Accepted Answer
MathWorks Support Team
on 26 Feb 2018
The "fileattrib" function is written as a wrapper for the DOS "attrib" command on Windows. "attrib" cannot do all the operations that you expect and checking read or write access for directories may not return the expected result. Therefore, when you do "fileattrib" on a directory, "UserRead" and "UserWrite" does not reliably report the read and write access to the directory in question.
One workaround to check read access to a folder is:
exist( myfolder, 'dir' ) && ~isempty( dir( myfolder ) )
To check if the user has write permission:
fileName = '\\path\to\my\folder\tmpFile.txt';
[fid,errmsg] = fopen(fileName, 'w');
if ~isempty(errmsg)&&strcmp(errmsg,'Permission denied')
fprintf('\nError: You do not have write permission to the folder (%s).\n',fileName);
else
fclose(fid);
delete(fileName);
end
Disclaimer : The above script deletes the file. Please take a backup of the file before running the script
1 Comment
Walter Roberson
on 25 Aug 2020
Not exactly. It is possible to have write access to an existing file without having write access to the directory, so 'a' vs 'w' is not exactly the same test. However the operating system documentation would have to be studied to find out whether requesting w access to an existing file is considered to be the same as deleting the file and recreating it. The POSIX answer would be No, that writing with 'w' keeps existing attributes while truncating the content, but Windows does not follow POSIX anymore.
More Answers (0)
See Also
Categories
Find more on File Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!