Quote:

fwrite() does right with int, so not sure how would I write double with it.




Not quite right. fwrite() takes a *void* pointer, and writes the memory that the pointer points to.

I think I see your confusion. You need to understand how variables are allocated space and are referenced. It is one of the more complicated areas, but opens up a whole new world of programming.

I'll give a short explanation, but you really need to get a good book. I still use my original K&R 'C' book - it is invaluable.

Ok, here's how it works. Variables are simply contiguous memory locations. You can think of them in exactly the same way as the data in your file. Different types of data require different numbers of contiguous bytes.

(I'm assuming 1 memory word=1 byte=8 bits for this explanation)
char=1 byte
unsigned char=1 byte
short int=2 bytes
long int=4 bytes
double presicion float=8 bytes
Note, different architectures will have differ requirements.

Now normally you access the variable by it's name. This is in fact (resolved to) a pointer to the location in memory. The compiler knows how big the variable is, so knows how much memory to read or write when the variable is accessed.

When your code says:
Code:
int i
i=10;



The first line declares a variable "i" which reserves 4 bytes of memory and sets "i" to point to that memory. The second line writes the value 10 in byte order to the memory location.

Now the tricky bit. You can get the address of the variable by using the "&" operator. This means that you can access the memory *directly*.

Here is a very simple example:
Code:
#include <stdio.h>

int main()
{
int i;
char c[sizeof(int)]; /* c is a pointer to an array of chars (a string) the same length as an int */

i=7827319;

memcpy(&c,&i,sizeof(i)); /* copy bytes from int to string */

printf("%d=%s\n",i,c);
return 0;
}



The "sizeof" operator returns the size (in bytes) of the data type.

The example code declares i as an int, then c as an array of chars, the same size as an int.

We assign a value to the int, and then use memcpy() to copy the memory pointed to by i (&i) to that pointed to by c (&c). "sizeof" is used to determine how many bytes to copy.

The result is a very short message:
Quote:

7827319=wow




You can do exactly the same thing will all variable types.

This means that you can use fread/fwrite to read and write any type of data without losing information.

If I take one of my earlier examples:
Code:
void fnWriteStringAsDOUBLE(FILE *fp,char *s)
{
double d;
d=atof(s);
fwrite(&d,sizeof d,1,fp);
}


Here, fwrite() is passed the *address* of the double (&d). It is also told how big the data is (sizeof d), and that we are writing one instance.

This will cause the memory containing the value of "d" to be written to disk, in this case 8 bytes.

fread() does exactly the same thing in reverse.

BTW, where was the quote from?