Reading to end-of-file

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Reading to end-of-file

Eyal Doron
Hi all!

Suppose I have a file try.dat:

 1 2
 2 3
 3 4
 4 5

and I want to read it using fscanf, but I don't know the length. I try

function a=try(f);
%
while !feof(f)
  s=fscanf(f,"%s"); g=fscanf(f,"%g");
  printf("%s, %g\n",s,g)
end

but this fails with an error,

warning: fscanf: end of file reached before final conversion
error: value on right hand side of assignment is undefined
error: evaluating assignment expression near line 4, column 4
error: evaluating while command near line 3, column 1
error: called from `try' in file `/us0/theo/doron/tmp/try.m'

I found no way around this, even unwind_protect is no help inside a
function. What to do?

It seems fscanf behaves quite badly at eof. IMHO it should not fail,
but explicitly return [] so that assignments don't crash.

P.S. This is just an example, so don't tell me there are other ways
to load this file!

Thanks,
    Eyal Doron

Reply | Threaded
Open this post in threaded view
|

Re: Reading to end-of-file

Christoph Mecklenbraeuker-2

Hi Eyal, the following code would give you the number of lines in the
file on a UNIX Machine. (Sorry, if you happen to work with a different OS)
Maybe this is of help? I know, this is not really satisfactory, but would
show a way, how to avoid reading beyond the EOF mark of a text-file.

>>     filename = "try.dat";
>>     cmd = sprintf("nl %s | tail -1 | awk - '{print $1;}'",filename);
>>     N = sscanf(system(cmd),"%d");

all the best,
Christoph

============= email: [hidden email] =======================
Christoph Mecklenbraeuker             |
Lehrstuhl f. Signaltheorie (IC 5/35)  | Tel: +49(234) 700 6119
Ruhr Universitaet Bochum              | Fax: +49(234) 709 4261
D-44780 Bochum, Germany               |
======== http://www.sth.ruhr-uni-bochum.de/sth/whois/cfm/cfm.html =====