MATLAB: How to use waitbar to show file copying status

progressbarwaitbar

This is my code under a push button in GUI. I want that it should show the progress of the file copying status with the use of "waitbar" command or by any other means .It will be very helpful if someone can provide a sample code, though help are available in matlab but I m unable to figure it out how it can be used for displaying file copying status. Thanks
% --- Executes on button press in pushbutton44.
function pushbutton44_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton44 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global dirpath_import;
dirpath_import= uigetdir();
set(handles.edit38,'String',dirpath_import);
importpath=get(handles.edit38,'String');
exportpath=get(handles.edit1,'String');
copyfile(importpath,exportpath);
msgbox('Import/Copy Complete');

Best Answer

While it does not matter, that the code is part of a callback, the relevant part is only:
copyfile(importpath, exportpath)
During this command Matlab is blocked an there is no chance for any progress indicators. If this is really required, you can create your own function to copy the file in blocks of e.g. 1MB:
function myCopyFile(source, dest)
FileInfo = dir(source);
FileSize = FileInfo.bytes;
waitH = waitbar(0, sprintf('Copying %.2f MB', FileSize/1e6);
inFID = fopen(source, 'r');
if inFID == -1
error('Cannot open file for reading: %s', source);
end
outFID = fopen(dest, 'w');
if outFID == -1,
fclose(inFID);
error('Cannot open file for writing: %s', dest);
end
chunk = 1e6;
nChunk = ceil(FileSize / chunk);
iChunk = 0;
while ~feof(inFID)
iChunk = iChunk + 1;
waitbar(iChunk / nChunk, waitH);
data = fread(inFID, chunk, '*uint8');
fwrite(outFID, data, 'uint8');
end
fclose(inFID);
fclose(outFID);
end
UNTESTED
Attention: File handling is a critical job. If the disk is full or the destination is on a network drive and loosing the connection, this cheap and naive implementation of a copyfile does not show a warning and might leave the file system in a corrupted state. The user can kill the copying by Ctrl-c also. I would not dare to do this in a productive system. Care for backups. Check the file system. Insert consistency checks, e.g. by counting the number or read and written bytes by catching the output of fread and fwrite.
Related Question