|Fundamental C - Random Access Files|
|Written by Harry Fairhead|
|Monday, 21 February 2022|
Page 2 of 2
You can use the same technique to position the file for a write to update a record. A modify is implemented by reading the record changing the value and then writing it again but notice that you need to position the file again to avoid undefined behavior:
fseek(f, record * sizeof (struct person), SEEK_SET); read(&me2, sizeof (struct person), 1, f); me2.age++; fseek(f, record * sizeof (struct person), SEEK_SET); fwrite(&me2, sizeof (struct person), 1, f);
Notice that the fseek before the fwrite is logically needed to position the file back to the start of the record after reading it. File reading and writing is always sequential after a positioning.
New records are added by simply moving the end of the file and writing. On a POSIX system you can also add a record beyond the end of the file and the missing records will be read as zeros until real data is written. For example:
fseek(f, 25 * sizeof (struct person), SEEK_SET); fwrite(&me, sizeof (struct person), 1, f);
writes a record at the 25th position, filling in the gap with zeros. That is, if you read record 24 the string will be a null string and the age will be zero.
This is all fine if you only want to find a record by a sequential record number, but what if you want to find a record by the value in a field? To implement this you need a lookup table that stores the field value and the record number that gives its location in the file. This lookup table is often created as another file which is read into memory for efficiency and is generally called an index. You can continue this line of thought until you have implemented a database, but it is usually a lot less work to make use of, or even modify, an existing database program.
The important point is that you can see how easy it is to use a random access file to store, retrieve and update data.
Sharing Files – Locking
Files, or more generally streams, are sometimes used as a communication channel between different processes, different programs and even different machines. The idea is that a file can be read and written by more than one agent. If files are shared then there is the problem of simultaneous update. The solution is to use a lock to restrict who can access it. There are locking functions provided by POSIX but they aren’t reliable and a much better solution is to use general resource locking mechanisms. You will also encounter the idea of a lock file. This is just a dummy file that is tested for to determine if another process has the file open already. These topics are covered in Applying C For The IoT With Linux ISBN: 978-1871962611.
Fundamental C: Getting Closer To The Machine
Now available as a paperback and ebook from Amazon.
Also see the companion volume: Applying C
or email your comment to: firstname.lastname@example.org
|Last Updated ( Tuesday, 22 February 2022 )|