0

我试图编写一个代码来检查文件是否打开。如果是这样,当文件没有关闭时,屏幕上会打印一条警告消息。

我想我没有正确使用“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
4

1 回答 1

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
于 2012-10-01T21:11:05.340 回答