Using filepath input in fopen

3 ビュー (過去 30 日間)
Suha
Suha 2017 年 8 月 17 日
コメント済み: Suha 2017 年 8 月 17 日
Hi all, I can't seem to use fopen to open a file using a variable that stores the name and path of the file. For example, the variable [pathvariable] stores /imper/codec/data.txt. I am doing fid = fopen([pathvariable],'r') but it is not working.
I've tried the following too:
fid = fopen(pathvariable,'r')
fid = fopen('pathvariable','r')
In all cases, I get a fid of -1.
Could someone please help. Thanks.
  3 件のコメント
Stephen23
Stephen23 2017 年 8 月 17 日
@Suha: in 99 percent of cases the filepath is incorrect or there is a spelling mistake somewhere. Check the filename carefully.
Suha
Suha 2017 年 8 月 17 日
Thank you KSSV and Stephen for your prompt reply ! My pathvariable was indeed the issue, which I have now fixed. :)

サインインしてコメントする。

採用された回答

Guillaume
Guillaume 2017 年 8 月 17 日
The proper syntax is indeed your first example:
fid = fopen(pathvariable, 'r');
There could be many reasons for why it does not work: invalid path(file not found), file locked, permission denied, etc. First thing to do would be to look at the errmsg output of:
[fid, errmsg] = fopen(pathvariable, 'r')
which should give you more info.
If you're on Windows, /imper/codec/data.txt does not look like a absolute path which may be the problem. I would always use absolute paths with fopen to avoid any issue:
fid = fopen(fullfile('C:\some\where', relativepath), 'r');
  1 件のコメント
Suha
Suha 2017 年 8 月 17 日
Thank you Guillaume for taking time out to write such a clear and detailed response. Much appreciated. Using the errmsg output I was able to spot that my pathvariable was incorrect, hence the file could not be detected. All fixed and working now. Many thanks !!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeEntering Commands についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by