title: Reading and writing binary files (GrADS) in fortran
body: <p>I am running a model and writing the model output to a binary file (a GrADS *gra file) such that, for example:</p>
  
  <pre><code>integer,parameter :: nvar =3 ,&amp; !number of variables to be written to file
                       nx=10,ny=10,&amp; !number of girdboxes in lat &amp; long
                       nt = 5
  integer :: it, &amp; ! loop counter
             irec  ! Record number
  real :: var1(nx,ny), var2(nx,ny),var3(nx,ny)
  
  OPEN(30,file='Outfile.gra',action='write',form='unformatted',access='direct',&amp;
      recl=4*nVar*nx*ny,status='replace')
  !loop over timesteps
  it  = 1, nt
      irec = irec + 1
      WRITE(1,rec=irec) Var1(:,:),Var2(:,:),Var3(:,:)
  enddo
  </code></pre>
  
  <p>The file can be read in GrADS and the *ctl file looks like this</p>
  
  <pre><code>dset /mypath/Outfile.gra
  title MyTitle
  options little_endian
  xdef 10 linear 1 1
  ydef 10 linear 1 1
  zdef 1 linear 1.0 1.0
  tdef 5 linear 00:00Z01jan2012 1hr
  vars 3
  var1
  var2
  var3
  endvars
  </code></pre>
  
  <p>What I would like to do, from a separate program, is write all the x&amp;y of 1 variable at 1 timestep to a text file. I tried a number of ways but nothing has worked. My latest attempt is this one:</p>
  
  <pre><code>integer,parameter :: &amp;
         t = 3,        &amp; !Timestep I want to write to file
         field = 2,    &amp; !Variable I want to write to file      
         nvar =3 ,     &amp; !number of variables to be written to file
         nx=10,ny=10,  &amp; !number of girdboxes in lat &amp; long
         nt = 5          !number of timesteps
  inteǵer :: it,ix,iy,&amp;  ! loop counters
             irec        ! Record number
  real :: val(nx,ny)     ! Data to be written to file
  
  open(1,file='NewFile.txt',status='replace')
  open(2,file='Outfile.gra',action='read',form='unformatted',access='direct',&amp;
     recl=4*nVar*nx*ny,status='old')
  
  irec =  0
  
  do it = 1,nt
     irec=irec + nvar*nx*ny
     if(it == t) then
     irec = irec + (field-1)*nx*ny  
     do ix = 1,nx
       do iy = 1,ny
        irec=irec+1
      read(2,rec=irec) val(ix,iy)
   enddo
  enddo
  write(1,*) val(:,:)
  </code></pre>
  
  <p>This particular example gives me the following error</p>
  
  <blockquote>
    <p>Fortran runtime error: Non-existing record number</p>
  </blockquote>
  
  <p>but I tried other variations that did not give me any errors but simply didn't write what I was trying to write to file. Could somebody tell me what I am doing wrong and how to solve this? Thank you.</p>