e.g. one has a couple of arrays of ints or floats and a few integers to store. Is there a simplistic way to save them for later reloading without having to write a data format from scratch etc.?
views:
52answers:
4- netcdf (simpler interface)
- hdf5 (more powerful)
they are not simple, however few hours investment is worth it
The simplest option is to use serialize() / unserialize()
or json_encode() / json_decode()
. They'll convert any PHP data structure into a simple string which you can read elsewhere on any machine with PHP, or at least a json library.
If their size is fixed, you can just fwrite
them on the file, actually dumping their memory representation to disk (you can do it even if their size is not fixed, but things get a little bit more complicated).
int someInts[50];
double someDoubles[25];
FILE * fp;
/* Write */
fp = fopen(/* ... */);
fwrite(someInts, sizeof(someInts), 1, fp);
fwrite(someDoubles, sizeof(someDoubles), 1, fp);
fclose(fp);
/* Read */
fp = fopen(/* ... */);
fread(someInts, sizeof(someInts), 1, fp);
fread(someDoubles, sizeof(someDoubles), 1, fp);
fclose(fp);
(error handling omitted for brevity)
I don't think there are faster or simpler methods, but keep in mind that, if it's not just a toy project, you should add some headers (that you can handle as a structure to fwrite/fread) to make sure you're reading a file generated by your application.
A downside of this method is that it's more complicated to edit "by hand", and, if such files have to be passed between different platforms, you'll have troubles if the various platforms have different endianness and different sizes for the types stored. Note that you can workaround these problems, but the code will start to become more complicated.
Another alternative (that, however, being an SQL DB is felt "natural" not in every situation) may be to use an SQLite database: as they say on their site:
SQLite is an embedded SQL database engine. Unlike most other SQL databases, SQLite does not have a separate server process. SQLite reads and writes directly to ordinary disk files. A complete SQL database with multiple tables, indices, triggers, and views, is contained in a single disk file. The database file format is cross-platform - you can freely copy a database between 32-bit and 64-bit systems or between big-endian and little-endian architectures. These features make SQLite a popular choice as an Application File Format. Think of SQLite not as a replacement for Oracle but as a replacement for fopen()
(emphasis added to the features that match your requirements)
You may want to have a look at their "Appropriate Uses For SQLite" page.
You could always use the most portable way by using a textual representation and writing them to a file with fprintf and using %d for ints and %f (or %lf) for floats. This avoids any binary incompatibilities between platforms and is the Unix Way(TM). Reread using scanf (or sccanf) and that's it.