C结构写在文件上,Java开放 [英] C struct written in file, open with Java

查看:137
本文介绍了C结构写在文件上,Java开放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如在C I具有结构:

For example in C I have structure:

typedef struct {
    int number;
    double x1;
    double y1;
    double x2;
    double y2;
    double x3;
    double y3;
} CTRstruct;`

然后我把它写到文件 FWRITE(安培; TR,1,sizeof的(TR),FP); (TR - 其CTRstruct VAR,FP - 文件指针)

Then I write it to file fwrite(&tr, 1, sizeof(tr), fp); (tr - its CTRstruct var, fp - File pointer);

然后,我需要与Java读吧!我真的不知道如何从文件中读取结构......我试着用的ObjectInputStream(),最后的想法是用读来读它RandomAccessFile的(),但我也不知道如何...( readLong()的readDouble()也不起作用,它工作ofcource但不读取正确的数据)。因此,任何想法如何使用Java读取二进制文件的C结构?

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):

公共类MyDataInputStream扩展DataInputStream以{

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));
}


双就可以处理相同的方式(如使用int或长(8个字节)及再转换与本机FUNC翻一番)。


with double we can deal the same way (like with int or with long (8bytes) & then convert to double with native func).

推荐答案

您必须找出你在执行的架构使用何种尺寸与C类型(int,double),因而该字节顺序(感谢安德鲁·库克)程序而在Java中使用同​​样大小的类型。

You have to find out what size those C types (int, double) and which endianness (thanks andrew cooke) are used in the architecture you executed the program in and use same sized types in Java.

这篇关于C结构写在文件上,Java开放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆