C struct written in file, open with Java
- by DaunnC
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).