For example in C I have structure:
typedef struct {
int number;
double x1;
double y1;
double x2;
double y2;
double x3;
double y3;
} CTRstruct;`
Then I write it to file fwrite(&tr, 1, sizeof(tr), fp);
(tr - its CTRstruct var, fp - File pointer);
Then I need to read it with Java! I really don't know how to read struct from file... I tried to read it with ObjectInputStream()
, last idea is to read with RandomAccessFile()
but I also don't know how to... (readLong(), readDouble()
also doesn't work, it works ofcource but doesn't read correct data). So, any idea how to read C struct from binary file with Java?
If it's interesting, my version to read integer (but it's ugly, & I don't know what to do with double
):
public class MyDataInputStream extends DataInputStream{
public MyDataInputStream(InputStream AIs) {
super(AIs);
}
public int readInt1() throws IOException{
int ch1 = in.read();
int ch2 = in.read();
int ch3 = in.read();
int ch4 = in.read();
if ((ch1 | ch2 | ch3 | ch4) < 0)
throw new EOFException();
return ((ch4 << 24) + (ch3 << 16) + (ch2 << 8) + (ch1 << 0));
}
with double we can deal the same way (like with int or with long (8bytes) & then convert to double with native func).
You should not use fwrite
of the entire struct
, because you will inevitably run into issues with padding and endian-ness. The C side will dump the entire struct
the way it is in the memory, with all its gaps that the compiler puts in for performance etc. That's "the mother of non-portability"!
Instead, you should use protocol buffers, JSON, or some other mean of portable serialization to accomplish your task.
Use a library that serializes your data to disk. That will make reading it back into Java a whole lot easier. Make sure that the library uses a well-documented storage format.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With