[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Importing fixed field-width ascii data files with fscanf
From: |
John W. Eaton |
Subject: |
Importing fixed field-width ascii data files with fscanf |
Date: |
Fri, 17 Aug 2001 20:00:28 -0500 |
On 17-Aug-2001, E. Joshua Rigler <address@hidden> wrote:
| I need to read in a fixed format ascii file. Apparently the scanf
| functions ignore any kind of field width and precision information.
| Actually, they don't ignore it, but return an error if you try to
| specify them!!!
|
| Even if it's admittedly outdated, fixed-width ascii data files are very,
| very common. What's more, is that most such files make no consideration
| of field delimiters like white space. Is there any way to read these in
| in Octave?
|
| In case it's not obvious, consider the following sample ascii data
| file...
|
| 1 99.9
| 2 99.9
| 3-99.9
| 4 99.9
|
| What _should_ work (IMHO) as a template for scanf is something like...
|
| fid = fopen("foo.txt","r");
| val = fscanf(fid,"%i3%5.1");
|
| ...but it doesn't, and I can't find a way to read in a data file like
| this sample without actually altering the file by hand. I've looked
| through the list archives for anything pertaining to fscanf, and it
| seems nobody has had this problem before. I find this surprising, so I
| wonder if I'm just doing something really stupid.
For the file you show, you can read it with
fscanf (fid, "%i%4f")
Note that there is no precision specification in the scanf format,
just a max field width.
Also, whitespace is ignored, so if you have numbers in columns that
actually mash together, like say
XXXYYYZZZ
123456789
23456 89
23 56789
(where XXX, YYY, and ZZZ mark the columns you think you want to read)
you will probably find that scanf is not going to work very well for
you. A format like
"%3i%3i%3i"
will actually read the numbers
123 456 789 234 56 89 23 567 89
and not
123 456 789 23 456 89 23 56 789
For cases like this, you'd probably need to read the file in as
text, then break it up first before scanning for numbers. For
example, some variation on
line = fgetl (fid);
num1 = sscanf (s(1:3), "%i");
num2 = sscanf (s(4:6), "%i");
...
jwe
-------------------------------------------------------------
Octave is freely available under the terms of the GNU GPL.
Octave's home on the web: http://www.octave.org
How to fund new projects: http://www.octave.org/funding.html
Subscription information: http://www.octave.org/archive.html
-------------------------------------------------------------