简体   繁体   中英

Fortran read binary file from C#

I am trying to read a binary in fortran. The file is created in c#. In my example below it just stores to integer (4 byte I assume since the created file size is 8 byte):

string binfile = @"c:\..\bindata.dat";
int nrecs = 60*60*24*61;
int nvalues = 34;

using (BinaryWriter bw = new BinaryWriter(File.Open(binfile, FileMode.Create)))
      {
        bw.Write(nrecs);
        bw.Write(nValues);        
      }

The fortran code to read the data :

program TestFortran

    implicit none

    ! Variables
    character(*),parameter      ::  fn = "bindata.dat"
    integer                     ::  numMeas,numVals
    integer                     ::  infile,ios
    character(len=11)           ::   acc, seq, frm
    character(len=128)          ::  nam
    logical                     ::  ex,op
    integer                     :: irec, nr,p
    ! Body of TestFortran
    print *, 'Hello World'
    infile = 10
    open(unit = infile,file = fn,status='OLD',access='STREAM',FORM='UNFORMATTED',action='READ',iostat=ios)
    inquire(infile,err=99,exist=ex,opened=op,name=nam,access=acc,&
      sequential= seq, form = frm, recl=irec, nextrec=nr,pos=p)
    read(infile,IOSTAT=ios)  numMeas
    read(infile,IOSTAT=ios)  numVals
99  close(infile)
    write(*,'(a,i8,a,i6)')  "Number of measurements = ", numMeas, ", and number of values in a measurement = ", numVals

end program TestFortran

The open and the inquire commands runs wihtout problem. In debug-mode it reports that after open ios is 0 and after inquire acc = 'STREAM', ex = .true., frm='UNFORMATTED', irec = -1, nam is the full path to the file, nr = 0, op = .true., p = 1 and seq = 'YES'.

when I run the first read statement ios = -1 indicating end-of-file and numMeas is not set to anything, same goes for read statement 2.

Does anyone knows what is wrong here? Every hint is much appreciated. I have tried to search for hints but haven't succeded in finding out what's going wrong...

so stupid of me... During debugging I had first tried without all the verifications, iostats, inquire etc.. I had also not included the status='OLD' in the open statement, whereby a 0 sized file had been created in the ../../ (base project folder) and not where I thought it should have been (in the /TestFortran/Debug/ directory ). Sorry guys for using your time in vain. But thanks for your quick responses.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM