matlab:检查xls文件是否打开

时间:2012-10-01 20:26:24

标签: matlab fopen fclose

我尝试编写一个代码来检查文件是否已打开。如果是这样,当文件未关闭时,屏幕上会显示一条警告信息。

我想我没有正确使用'fclose',因为通过这种方式,我收到了错误:

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

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

我试过没有fclose函数,它可以工作,但是当我打开文件时,我收到一条消息,说该文件只是用于阅读。

这是我的代码:

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

1 个答案:

答案 0 :(得分:0)

我成功了!这是解决方案:

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