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

6 views (last 30 days)
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?

Accepted Answer

Pat Canny
Pat Canny on 13 Aug 2021
Edited: Pat Canny on 13 Aug 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 Comment
Stephen23
Stephen23 on 13 Aug 2021
Edited: Stephen23 on 13 Aug 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.)"

Sign in to comment.

More Answers (0)

Categories

Find more on File Operations in Help Center and File Exchange

Tags

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!