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

12 visualizaciones (últimos 30 días)
Pat Canny
Pat Canny el 13 de Ag. de 2021
Editada: Stephen23 el 13 de Ag. de 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?

Respuesta aceptada

Pat Canny
Pat Canny el 13 de Ag. de 2021
Editada: Pat Canny el 13 de Ag. de 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 comentario
Stephen23
Stephen23 el 13 de Ag. de 2021
Editada: Stephen23 el 13 de Ag. de 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.)"

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre File Operations en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by