How to read and write float numbers from and into binary files? [duplicate]
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");
}
精彩评论