2 回答

TA貢獻1780條經驗 獲得超1個贊
我的 Java 有點生疏,但看起來你寫入文件的內容是三個 4 字節整數,按順序和機器字節順序(所以可能是小端序)。這意味著您的文件應該具有(十六進制):
9a 00 00 00 62 00 00 00 06 00 00 00
但是您的掃描預計會將數字視為以空格分隔的文本,例如(以十六進制表示)
31 35 34 20 39 38 20 36 0a
你可能應該使用類似的東西fread()
,它不做解析:
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
并且目標應該是類似的地址int[3]
。

TA貢獻1852條經驗 獲得超1個贊
我知道fscanf讀取一個字符流,然后根據給定的格式對其進行解析。這意味著我們應該以 C 支持的字符格式用 Java 編寫文件。
這就是我所做的:
Java代碼:
package scratchpad;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
public class WriteClass {
void writeFunction() {
File defgFile = new File("/home/thor/Documents/ScratchPad/def.bin");
try(FileOutputStream fos = new FileOutputStream(defgFile)){
BufferedWriter bos = new BufferedWriter(new OutputStreamWriter(fos,StandardCharsets.US_ASCII));
bos.write(Integer.toString(123));
bos.newLine();
bos.write(Integer.toString(96));
bos.newLine();
bos.write(Integer.toString(1));
bos.newLine();
bos.write("Water");
bos.newLine();
bos.write(Integer.toString(2));
bos.newLine();
bos.write("Forest");
bos.newLine();
bos.flush();
bos.close();
}
catch(IOException ex) {
Logger.getLogger(WriteClass.class.getName()).log(Level.SEVERE,"Can't open a new file",ex);
}
}
}
需要注意的重要一點是,我曾經OutputStreamWriter以 ASCII 格式編寫文本文件。另一點是我們不必擔心ByteOrder將 ASCII 值寫入文件的位置。似乎Java正在處理它。
獨立于平臺的bos.newLine()方式來編寫一個新行。 bos.flush()是強制性的,否則數據將不會被寫入。
C代碼:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
FILE *fp = fopen("def.bin","r");
int one,two,three;
fscanf(fp,"%d",&one);
fscanf(fp,"%d",&two);
printf("%d\n%d\n",one,two);
int index;
fscanf(fp,"%d",&index);
char* string;
fscanf(fp,"%s",string);
printf("%d\n%s\n",classno,string);
return 0;
}
我注意到字符串char*沒有分配內存并且仍然有效。
添加回答
舉報