Error opening a text file using fopen

3 Ansichten (letzte 30 Tage)
Add
Add am 25 Mär. 2016
Kommentiert: Walter Roberson am 25 Mär. 2016
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 Kommentare
Stephen23
Stephen23 am 25 Mär. 2016
Bearbeitet: Stephen23 am 25 Mär. 2016
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 am 25 Mär. 2016
I tried your suggestion but then it says
Error using sprintf
Function is not defined for 'cell' inputs.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Star Strider
Star Strider am 25 Mär. 2016
‘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 Kommentare
Add
Add am 25 Mär. 2016
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 am 25 Mär. 2016
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()

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by