How do I check to see if any file in a directory is locked?

12 vues (au cours des 30 derniers jours)
Pat Canny
Pat Canny le 13 Août 2021
Modifié(e) : Stephen23 le 13 Août 2021
I consume a nightly automated query which generates over 100 files and places them in a given directory.
If any of the files in the directory are locked for editing by another user, the "job" won't complete.
Is there a way in MATLAB to check to see if any file in a given directory is locked?

Réponse acceptée

Pat Canny
Pat Canny le 13 Août 2021
Modifié(e) : Pat Canny le 13 Août 2021
There is a function in the MATLAB Report Generator utilities called "isFileLocked".
Here is one way to use that function to check to see if any file in a given directory is locked.
aFolder = "\\someDirectory\someSubdirectory";
filesInFolder = dir(aFolder);
fileNames = string({filesInFolder(3:end).name})'; % the first two items are not actual file names
numFiles = numel(fileNames);
fileLocked = false(1,numFiles);
for i=1:numFiles
thisfileName = fullfile(aFolder,fileNames(i));
fileLocked(i) = mlreportgen.utils.isFileLocked(thisfileName);
end
if any(fileLocked)
disp("A file is locked")
lockedFiles = fileNames(fileLocked)
else
disp("No files are locked. All is well!")
end
  1 commentaire
Stephen23
Stephen23 le 13 Août 2021
Modifié(e) : Stephen23 le 13 Août 2021
"the first two items are not actual file name"
This is incorrect, as any regular reader of this forum will know.
It is also very easy to demonstrate that it is incorrect:
fclose(fopen('+2.txt','w'));
S = dir();
S.name
ans = '+2.txt'
ans = '.'
ans = '..'
S.isdir
ans = logical
0
ans = logical
1
ans = logical
1
Learn more here:
As Walter Roberson wrote in that last link: "In short: if your code assumes that '.' and '..' are the first two entries in a directory, your code has a bug (even in MS Windows). If your code assumes that directory entries are returned in any sorted order, your code has a bug (in all OS.)"

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur File Operations dans Help Center et File Exchange

Tags

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by