Why does fopen fail to find a file?
20 次查看(过去 30 天)
显示 更早的评论
I'm using fopen within a function. The name of the file to be opened is passed in the function argument, so it looks like:
function [x y z] = myfun(finp)
...
[fid msg] = fopen(finp,'rt')
The file exists, but I get the 'No such file or directory' message. However, if I just enter fopen(finp,'rt') at the command line (after having run the main code, so finp is defined exactly as passed to the function), I get no error and a positive fid value.
The file itself is in a remote directory, eg ~/Dir1/Dir2/file. If, inside the function, I cd to Dir1, then fopen('Dir2/file','rt'), it works. However, I'd rather not have to do this if possible.
Any suggestions?
0 个评论
回答(3 个)
Jan
2013-8-30
Of course you have to define the folder in which the file is found, if this is not the current folder.
finp = fullfile('~/Dir1/Dir2/', file);
[x,y,z] = myfun(finp)
There is no other way, because different folders can contain files with the same name. To solve such ambiguities, the folder is required to define the path to the file uniquely.
Azzi Abdelmalek
2013-8-30
You have to specify the folder and the filename, for example
folder='E:\matlab'
file='yourfilename'
finp=fullfile(folder,file)
[x y z] = myfun(finp)
2 个评论
Walter Roberson
2013-8-30
Are you using the '~' as part of the string you are passing in? ~ is a shell-level shortcut, not an operating-system shortcut, so routines such as fopen() are allowed to not understand it (or to understand it inconsistently) unless they are documented to know about it.
3 个评论
Walter Roberson
2013-8-30
To check: you have displayed the filename and current directory just before the fopen() in each case and verified them to be the same ?
Jan
2013-8-30
@Will: I do not believe that such a magic behavior is the reason for the problems. Either there is a typo or your program performs some important steps you did not explain yet, e.g. logging on to an external server or things like that.
What does this mean exactly: "I'm doing so in the same (remote) working directory as the function that generates the error works in."?
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Low-Level File I/O 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!