Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to use C to read data writen with Java

Status
Not open for further replies.

zhanghong920

Programmer
Nov 15, 2002
27
US
I use a Java program to write a matrix data into a file using: DataOutputStream.write() and .writeLong(). But I need to use a C program to read the matrix data. How can I do that?

My Java code (to write the matrix)is:

matrixFile.write(nrow);
matrixFile.write(ncol);
matrixFile.write(nonzero);
for(int i = 0; i < ncol; i++)
matrixFile.writeLong(pointr);

My C code (to read the matrix) is:

fscanf(fp_in2,&quot;%d%d%d&quot;,&ncol,&nrow,&nnzero);
for (i = 0; i <= ncol; i++)
fscanf(fp_in2, &quot;%ld&quot;, &pointr);

But I got 0 for &quot;nrow&quot;, &quot;ncol&quot; and &quot;nonzero&quot;, and thus no value from pointr since ncol is 0.

Any suggestions or hints are appreciated. Thanks,

Hong
 
Hi zhanghong:

Could you post a sample output file from your Java program? it would be useful to see it. Anyway, you must take in count a few things. First, when you use write(int b), the method writes the low eight bits of the argument b to the underlying output stream. It means that if you have a column or row number greater than 255 it wont work.
Second, it writes the integers with no end of line, so I think that your file should be like this:
34501.22.31.2 ...
I dont rememeber if the fscanf funtction reads until it reaches the end of line (i.e. it looks for three integers &quot;%d%d%d&quot; and the end of line (\r\n). To write end of lines I use writeBytes(line+&quot;\n&quot;) where line contains the integer.

You must check that, but to be sure please post a sample output file.

Hope it helps.

Pedro.
 
I think you should be using fread. Be careful that the byte order is consistent. Java uses a specific byte order convention for DataOutputStream.writeLong:


Whereas the order in which longs are interpreted in C can vary from platform to platform. Java 1.4 introduces the new package java.nio which allows you to set a ByteOrder:


I hope this helps. :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top