What causes an invalid file identifier in MATLAB?

2019-01-15 10:22发布

I have a MATLAB script that I could have sworn worked fine the last time I used it (a year ago). Now, I get this error:

Invalid file identifier.  Use fopen to generate a valid file identifier.

If I understand correctly, it is failing to find or open(?) a file specified elsewhere in the script. Is this right? If so, what could cause it?

标签: matlab fopen
11条回答
Fickle 薄情
2楼-- · 2019-01-15 10:28

For my situation, I have checked everything, but missed an easy step.

Please select "browse your folder" and browse for your current document location before you run your 'fopen' code.

enter image description here

查看更多
ゆ 、 Hurt°
3楼-- · 2019-01-15 10:30

I solved this problem for my self by adding permission option to fopen. As you see in http://www.mathworks.se/help/matlab/ref/fopen.html , fopen syntax is:

fileID = fopen(filename,permission)

Possible permissions, for example are: 'r' (default) | 'w' | 'a' | 'r+' | 'w+' | 'a+' | ...

'r' – Open file for reading.

'w' – Open or create new file for writing. Discard existing contents, if any.

'a' – Open or create new file for writing. Append data to the end of the file.

'r+' – Open file for reading and writing.

'w+' – Open or create new file for reading and writing. Discard existing contents, if any.

'a+' – Open or create new file for reading and writing. Append data to the end of the file.

...

If I use fopen without permission option, or if I use 'r' (default) option, fopen will return -1, which is error. I success with this:

fid=fopen('tmp.txt', 'w');
fid=fopen('tmp.txt', 'a');
查看更多
我命由我不由天
4楼-- · 2019-01-15 10:30

I had this problem. It turned out that the file I was trying to write was too large (I didn't have enough free space to accommodate it). However, the program didn't fail until the call to fclose. Very confusing!

Try freeing up some space, or writing a very small file, to test this diagnosis.

查看更多
倾城 Initia
5楼-- · 2019-01-15 10:31

I had the file opened in excel and as a result fopen returned a -1. Took me forever to find such a trivial problem.

查看更多
看我几分像从前
6楼-- · 2019-01-15 10:31

It also happens when trying to create a file in a non-existent directory. Try mkdir('folderName') within MATLAB or just create the directory beforehand.

查看更多
在下西门庆
7楼-- · 2019-01-15 10:32

The path with a forward slash at the beginning can cause the same error.

filename = '/data/myfile.txt';

throws this error, while

filename = 'data/myfile.txt';

does not produce an error.

查看更多
登录 后发表回答