Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

getline inside a do-while statement

Status
Not open for further replies.

holaqtal

Programmer
May 6, 2003
7
ES
i'm trying to basically read every line of a file, doesn't really matter in what order, and look for two fields that match a pattern (dest=M,type=N) and return the third field, something like:

dest1 type1 .99
dest2 type2 2.34
dest3 type3 .50

To do this I'd have to be able to go back to the beginning of the file once it reaches the end because when i call the function with a diferent destination and type it starts where it left off. And once it reaches the end of the file it goes crazy. I tried modifying the NR,FNR variables but that didn't do anything

The function is something like:

awk '
function price(dest,type)
{
do{
getline pri < &quot;Rates&quot;
split(pri,a,&quot; &quot;)
}while ((a[1]!=dest)&&(a[2]!=type))
return a[3]
}
.
.
.
where &quot;Rates&quot;

dest1 type1 .99
dest2 type2 2.34
dest3 type3 .50



Any help would be thanked profusely.
 
Awk does not allow this type of operation.
Getline reads the next line and advances the read
pointer, there is no similar function that resets
the read pointer to a previous record.


The likeliest thing is to store the file contents in
an array and work with the array.

Code:
function price(array,dest,type,max, f) {
f=0
        do {
            printf(&quot;Presplit at %d = %s\n&quot;, f, array[f])
            split(array[f++],a)
            printf(&quot;Looking at fld1 %s and fld2 %s\n&quot;, a[1],a[2])
        } while ( a[1] != dest && a[2] != type && f <= max)
return a[3]
}

function readFile(fname,arra, a) {
a=0
         while ((getline arra[a++] < fname) > 0) {
                #nada
          }
return a
}

BEGIN {
        hold[1] = &quot;&quot;
        m = readFile(ARGV[1],hold)
        price(hold,&quot;inner&quot;,&quot;outer&quot;,m)
}
 
holaqtal,
FYI:
Code:
function price(dest,type){
  do{
    getline pri < &quot;Rates&quot;
    split(pri,a,&quot; &quot;)
  }while((a[1]!=dest)&&(a[2]!=type))
  close(&quot;Rates&quot;) #<----- missing statement in your script
  return a[3]
}
will do (inefficiently) what you wanted.

Hope This Help
PH.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top