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

6 次查看(过去 30 天)
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?

采纳的回答

Pat Canny
Pat Canny 2021-8-13
编辑:Pat Canny 2021-8-13
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 个评论
Stephen23
Stephen23 2021-8-13
编辑:Stephen23 2021-8-13
"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.)"

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 File Operations 的更多信息

标签

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by