Search code examples
matlabfopenfclose

matlab: check if xls file is open


I tried to write a code that checks if the file is open. if so, while the file is not closed, a warning message will printed to the screen.

I guess I didn't use the 'fclose' correctly because by this way, I got the error:

??? Error using ==> fclose
Invalid file identifier.  Use fopen to generate a valid file identifier.

Error in ==> fileisopen at 4
fclose(fid);

I tried without the fclose function, it works, but when I opened the file I got a message that the file is only for reading.

this is my code:

path_of_file = 'C:\Documents and Settings\erezalon\Desktop\data.xls';

[fid msg_file] = fopen(path_of_file, 'a');
fclose(fid);
while (fid == -1)
    errormsg = strcat('the file: ', path_of_file, ' is open. please close it!');
    waitfor(msgbox(errormsg,'Error'));
    [fid msg_file] = fopen(path_of_file, 'a');
    fclose(fid);
end

Solution

  • I succeded! this is the solution:

    path_of_file = 'C:\Documents and Settings\erezalon\Desktop\data2.xls';
    
    fid = fopen(path_of_file, 'a');
    if fid ~= -1
        fclose(fid);
    else
        while (fid == -1)
            errormsg = strcat('the file: ', path_of_file, ' is open. please close it!');
            waitfor(msgbox(errormsg,'Error'));
            fid = fopen(path_of_file, 'a');
        end
        fclose(fid);
    end