0

If I write data to a file as follows:

program main

  implicit none

  integer :: err
  real (kind=4), dimension(3) :: buffer

  buffer(1) = 1.2
  buffer(2) = 3.7
  buffer(3) = 0.1

  open(unit=36, file='test.dat', iostat=err, form='unformatted', action='write', status='new')

  write(36) buffer

  close(36)

end program

I would expect the file to be 12 bytes since the size of the real data type is 4 and I am inserting 3 real values in the file (4x3=12). However, if I type the following in my shell:

$ ls -lh test.dat

it says the file is 20 bytes.

G. LC
  • 794
  • 1
  • 8
  • 27
  • A big misunderstanding, as written many times on stack overflow, is that `kind=4` is 4 bytes although in your case it is correct. You are writing unformatted, so some record information is written as well (most of the times the length of the record, in 4 bytes before and after the record. As there is no information about the compiler it is hard to say exactly what is writte, just have a look wit e.g. od, octal dump, at the file). – albert Jul 19 '19 at 12:48
  • @albert Thanks I'll take a look, I compiled with gfortran by the way. – G. LC Jul 19 '19 at 12:52

1 Answers1

2

Fortran unformatted files are not "binary" files, they still have a record structure. Thus typically there will be extra data over and above that which you have written to store information about the record - typically this is the length of the record, or maybe an end of record marker. Thus your file is bigger than the raw data.

Also don't use explicit constants for kind numbers - I can show you compilers where real(4) will fail to compile. Instead use Selected_real_kind or similar, or use the constant in the intrinsic module iso_fortran_env, or possibly those in iso_c_binding.

Ian Bush
  • 6,996
  • 1
  • 21
  • 27