Why does fopen fail to find a file?
조회 수: 3 (최근 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에서 File Operations에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!