简体   繁体   中英

Read from a file written in C with Java

I have a binary file written in C and I want to read it in java. I wrote the file in C like this :

void Log(TCHAR *name,int age){
    write_int(file, 2012);
    write_int(file, 4);
    write_int(file, 16);
    write_int(file, 12);
    write_int(file, 58);
    write_int(file, 50);

    fwrite(&name, sizeof(name), 1, file);
    fwrite(&age, sizeof(age), 1, file);
    fflush(processusFile);
}

In Java I use the BinaryFile class http://www.heatonresearch.com/code/22/BinaryFile.java and I do this :

RandomAccessFile f = new RandomAccessFile("myfile.dat", "r");
BinaryFile binaryFile = new BinaryFile(f);
ArrayList<String> text = new ArrayList<>();
while (true) {
try {
    Calendar calendar = new GregorianCalendar();
    int year = (int) binaryFile.readDWord();
    int month = (int) binaryFile.readDWord();
    int date = (int) binaryFile.readDWord();
    int hourOfDay = (int) binaryFile.readDWord();
    int minute = (int) binaryFile.readDWord();
    int second = (int) binaryFile.readDWord();

    calendar.set(year, month, date, hourOfDay, minute, second); 
    System.out.println(binaryFile.readFixedString(64));    
    catch (Exception e) {
        break;  
    }
}

This is not working for char* but for int it works. How I can write Strings?

This is because sizeof(name) is the size of a char pointer on your system, not the length of the string. You need to write out the length separately from the string, too.

size_t len = strlen(name);
write_int(file, len);
fwrite(&name, len, sizeof(char), file);

You must take care type "int".

int in java is always 32bit, not so in C. In C it may be 16,32,64 bit

This is wrong:

fwrite(&name, sizeof(name), 1, file);

this will only write a number of characters that correspond to the size of the pointer , typically 4.

If the size you want to write out is fixed (looks like the Java code expects 64 characters), you need to pass that size somehow to Log() .

There is no way in C to figure out the size of the array that (might have been) was passed as the first argument to Log() from within the function, which is why you must make it explicit.

Your fwrite statement doesn't look right:

fwrite(&name, sizeof(name), 1, file);

You actually want something like:

fwrite(name, sizeof(TCHAR), strlen(name) + 1, file);

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