How can I check if I have read or write access to a directory?

38 visualizzazioni (ultimi 30 giorni)
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?

Risposta accettata

MathWorks Support Team
MathWorks Support Team il 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 Commento
Walter Roberson
Walter Roberson il 25 Ago 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.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su File Operations in Help Center e File Exchange

Tag

Non è stata ancora inserito alcun tag.

Prodotti


Release

R2016a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by