简体   繁体   中英

Reading a fortran generated binary file into a signed integer array in C++

I am learning C++. I want to read some files generated by a fortran program in a C++ program. Each of the files I want to read contains a list of numbers which are either 0, 1, or -1. These numbers are the elements of an array of 1-byte integers defined in the fortran program. A sample fortran code, as well as a sample C++ code (in which I try to read the file into an unsigned integer array, to start with), is written below. In the fortran code, I write an array of 1-byte integers in a binary file, then read that binary file into an array and print the array elements. When I try to read the same binary file into an array in the C++ code, and then print the array elements, the output is unexpected. Can someone help me in getting it right? It would be great if someone gives a C++ equivalent of the second do-loop from the fortran code. Since, I finally want to read the files into 1-byte signed integer arrays, what one would need for that?

fortran90 code:

    implicit none;
    integer*1 a(1:2),i
   open(10, file="binary.bin", access="stream", form="unformatted")
   do i=1,2,1
     a(i)=1
    write(10) a
   enddo
    close(unit=10)

   open(20, file="binary.bin", access="stream", form="unformatted")
   do i =1,2,1
    read(20) a(i)
    write(*,*) a
   enddo
   close(unit=20)

   end

Output:

1

1


C++ code:

#include <iostream>
#include <fstream>


int main()
{

int i = 1;
int j = 1;
int max_i = 2;
char a[2];

using namespace std;

std::ifstream myinputFile; 

myinputFile.open ("binary.bin", std::ios::in | std::ios::binary);

if (!myinputFile.is_open()) return false;

for (i = 1; i <= max_i; ++i) { 
  myinputFile.read (a, 2);
  std::cout << i <<" "<< a[i] << std::endl ;
}

return 0;
}

Output:
1 

2 @
-----------
Expected output:

1 1

2 1

The problem is that char's are written as char's, not as integers. If you are using a C++11 compliant compiler, you could use the type std::int8_t type (defined in <cstdint> ) instead of char.

If you are using an older compiler, you should convert the char to an integer first before printing it, like this:

std::cout << i << static_cast<int>(a[i]) << std::endl;

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