Error opening a text file using fopen

3 次查看(过去 30 天)
I have this for loop running to read a series of text files
STA_NAME = CODE2(j);
filename = [STA_NAME day_num '-' date_str1 '.Cmn'];
Cmn_File = [Cmn_Dir '\' filename];
fid = fopen(Cmn_File);
CODE2(j) is fine. Cmn_Dir is also fine. But why it is showing an error in fopen.
Error using fopen, First input must be a file name of type char, or a file identifier of type double. ?? Can anyone solve this ?
  2 个评论
Stephen23
Stephen23 2016-3-25
编辑:Stephen23 2016-3-25
It is better to use sprintf to generate the filename and fullfile to join the the path parts together:
fnm = sprintf('%s%s-%s.Cnm', STA_NAME, day_num, date_str1);
pth = fullfile(Cmn_Dir, fnm);
fid = fopen(pth);
This will also generate clearer warnings when some parts are not compatible types.
Add
Add 2016-3-25
I tried your suggestion but then it says
Error using sprintf
Function is not defined for 'cell' inputs.

请先登录,再进行评论。

回答(1 个)

Star Strider
Star Strider 2016-3-25
‘Can anyone solve this ?’
Please post the string that is assigned to ‘Cmn_File’. (Remove the semicolon from the end of that line, and copy the result from the Command Window and paste it here.) We have no idea what the problem may be without seeing it.
  2 个评论
Add
Add 2016-3-25
The string assigned to Cmn_File is as follows
Cmn_File = [Cmn_Dir '\' filename];
And the result from the command window is as below
'D:\Adarsh\PhD\Da...' '\' 'hyde' '274' '-' '2013-10-01' '.Cmn'
Walter Roberson
Walter Roberson 2016-3-25
One or more of your components for Cmn_Dir or filename is a cell array of strings instead of being a plain string. The result of the [] then becomes a cell array of strings, and fopen() cannot process that.
While you are cleaning up the code, I recommend you switch to using fullfile()

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by