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

조회 수: 5 (최근 30일)
Pat Canny
Pat Canny 2021년 8월 13일
편집: Stephen23 2021년 8월 13일
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