开发者

How to read and write float numbers from and into binary files? [duplicate]

This question already has answers here: Serialize double and float with C (8 answers) Closed 4 years ago.

How should a program read and write float numbers from and into binary files in C or Vala language?

The common APIs to do writing and reading are generally designed to write in byte format. I mean you have to write arrays of one-byte data into file and read in the same format.

I'm looking for a way to write and read in fl开发者_运维百科oat format. without typecasting and without having to change the number into string. Is it possible?


fwrite() and fread() or write() and read() will work just fine.

float da, db ;
    ...
fwrite( &da, 1, sizeof(da), fpout ) ;
    ...
fread( &db, 1, sizeof(db), fpin ) ;


In Vala you can do:

public void main() {
    float foutvalue = 5.55;
    { //Need to make vala close the output file!
        var output = FileStream.open("floatfile","w");
        output.printf("%f", foutvalue);
    }

    float finvalue = 0.0;
    {
        var input = FileStream.open("floatfile", "r");
        input.scanf("%f", out finvalue);
    }
    print(@"$finvalue\n");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜