Why does fopen fail to find a file?

26 views (last 30 days)
Will Graham
Will Graham on 30 Aug 2013
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?

Answers (3)

Jan
Jan on 30 Aug 2013
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.
  1 Comment
Will Graham
Will Graham on 30 Aug 2013
This isn't the problem; finp contains the full pathname of the file. When I run fopen(finp,'rt') successfully from the command line, I'm doing so in the same (remote) working directory as the function that generates the error works in.

Sign in to comment.


Azzi Abdelmalek
Azzi Abdelmalek on 30 Aug 2013
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 Comments
Will Graham
Will Graham on 30 Aug 2013
Please see the comment that I've added to the first answer.
Azzi Abdelmalek
Azzi Abdelmalek on 30 Aug 2013
Post your function and how your are calling it

Sign in to comment.


Walter Roberson
Walter Roberson on 30 Aug 2013
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 Comments
Walter Roberson
Walter Roberson on 30 Aug 2013
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
Jan on 30 Aug 2013
@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."?

Sign in to comment.

Tags

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!