When you are working with binary files you have to establish and stick to a very regular format. Usually the simplest way to do this is to create a struct that has the data you want to save and load and make use of this to structure your file.
For example, a record might consist of a name and age. A suitable struct would be:
struct person me2;
f = fopen("myFile.bin", "rb");
fread(&me2, sizeof (struct person), 1, f);
fclose(f);
printf("%s %d", me2.name, me2.age);
Notice that the struct is treated as a single entity and all of the bytes it uses are written to the file and then read back in.
You can, of course, write multiple records and read multiple records back in one at a time if you want. The key idea is that rather than trying to structure the file by writing variables of different types it is much easier to create a suitable struct and read and write it as a single unit.
In chapter but not included in this extract:
Buffering
Character I/O
Positioning Functions
End Of File Errors
Random Access
File Operations
Sharing Files – Locking
Summary
If you think of a file as just a sequence or stream of bytes that can be read or written then you have an idea that fits a great many sources and sinks of data.
This idea is so powerful that under Linux/Unix you can view almost all data as an example of a file.
C has a standard way of working with files – streams – and it provides a range of functions for working with file pointers such as fopen and fclose.
In text mode a C file can be accessed using fprintf and fscanf which are file versions of printf and scanf.
In binary mode you can use fread and fwrite to work with binary data as sets of bytes.
The natural way to organize binary files is to use structs as if they were records.
C files are buffered and this can cause unexpected behavior. Use fflush to make sure that buffers are written out.
You can also use lower level character functions fgetc and fputc.
Files are read from the current position which can be changed using rewind or fseek. You can find the current position using ftell.
Detecting the end of a file is sometimes difficult as EOF is returned if there is an error as well as when the end of file has been reached.#
Using file positioning and structs it is very easy to implement a simple database.
There are a range of file manipulation commands that allow you to do things like rename files.
Linux/Unix file locking is troublesome and it is better to implement your own locking from first principles.
Fundamental C: Getting Closer To The Machine
Now available as a paperback and ebook from Amazon.
A novel investigation into the gender gap between men and women regarding coding ability was undertaken by Dr Siân Brooke. Her conclusion? There is a difference in the Python code [ ... ]
JetBrains has launched a non-commercial license for its JavaScript and TypeScript IDE, WebStorm, and for Rider, its cross-platform .NET and game development IDE.