Using files in C

The structure passed to the file function must be of type FILE
int countw;
FILE *file;
When opening, the file structure pointer will be NULL if it is not opened for some reason, either access control ( read only) ( wrong user ), doesn't exist, or even a file system failure. I use "wb" here to indicate I wish to open the file to write as a binary.
if ((file = fopen(filename, "wb"))==NULL)

Now writing, general form is:
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);

/* Writes data from the array pointed to by ptr to the given stream. It writes nmemb number of elements of size size. The total number of bytes written is (size*nmemb). On success the number of elements written is returned. On error the total number of elements successfully written (which may be zero) is returned. */

Here is an example of its use, in the save game function. I only use binary and an array of ints to save the game. Note the use of "sizeof(int)" specifically. So it requires a pointer to the data,an element size, number of elements to write, and, "FILE" structure pointer. It returns the count of actual elements written. The file needs to be closed when everything is done being written, so that it is actually instantiated on the disk. This happens at different times and with different methods depending on file system settings and the type of file system , such as ext3, ext4 etc. I suppose that has nothing to do with code, but I just threw it in, because I know that.

elementscountw=fwrite(puzzle,sizeof(int),6*6*6*2,file); countw=countw+fwrite(rules,sizeof(int),RULES_SIZE*RULES_LIMIT,file); fclose(file);

Something odd that I thought of while describing this is:   => If I have a system with sizeof(int)=4 and a system of sizeof(int)=2 and a game is saved on one system with a different int size, the saved game could not be sent and loaded on another system. How odd, I think I will make a file header that is some type of magic bytes that tells me what the sizeof(int) it thinks it is using. File magic is a whole nother topic so I will stop here.


Automated Intelligence

Automated Intelligence
Auftrag der unendlichen LOL katzen