How do I write an array to a binary file?
1 个评论
回答(2 个)
"binary file" means different things to different people.
The standardized "binary" formats that inherently support recording array sizes as well as array content, are typically a bit complex (because they have to be flexible). For example xlsb files are standardized but not internally simple. xlsx files turn out to be directories of text XML files that have been compressed. hdf5 files are pretty complicated and often slow in real use. cdf files require that you worry about defining hierarchies of attributes.
For simple arrays, most often programs use unstandardized binary files that are stored in whatever format is most convenient for the task. For fixed size arrays, a program would probably just fwrite() the array, and to read it back would either supply the expected array size to fread() or else would reshape() the vector results of fread to the expected fixed size.
For simple variable size arrays, it is common for programs to first fwrite array size information. But there is no special agreement about how many bytes are allocated to recording each dimension, or if the dimension information is saved as double for easy use, or whether all of the dimensions are recorded or just the number of rows or number of columns (you can deduce the other dimension by finding out the file size and dividing by the bytes per row or per column). Also no special agreement as to whether the number of dimensions is recorded first or if there are a fixed number of dimension slots with unused trailing dimensions set to 0 or set to 1 or set to the maximum integer...
Routine binary files only have whatever internal structure that the writing programs impose.
There were early attempts to standardize representation of binary formats so that reading programs would not have to have the same computer architecture and would not have to know ahead of time what the representation was. Standards such as XDR. I can count on one finger the number of times in several decades that I have seen XDR used for anything other than unix remote system calls.
0 个评论
另请参阅
类别
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!