Fundamental C - Random Access Files
Written by Harry Fairhead   
Monday, 21 February 2022
Article Index
Fundamental C - Random Access Files
Updates

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.

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.

 

 

 

Related Articles

Remote C/C++ Development With NetBeans

Raspberry Pi And The IoT In C

Getting Started With C/C++ On The Micro:bit

Fundamental C: Getting Closer To The Machine

Now available as a paperback and ebook from Amazon.

  1. About C
      Extract Dependent v Independent
                  & Undefined Behavio
  2. Getting Started With C Using NetBeans
  3. Control Structures and Data
  4. Variables
      Extract Variables 
  5. Arithmetic  and Representation
      Extract Arithmetic and Representation 
  6. Operators and Expression
      Extract: Expressions
      Extract Side Effects, Sequence Points And Lazy Evaluation
      First Draft of Chapter: Low Down Data
  7. Functions Scope and Lifetime
  8. Arrays
      Extract  Simple Arrays 
      Extract  Ennumerations 
  9. Strings
      Extract  Simple Strings
     
    Extract: String I/O ***NEW!!
  10. Pointers
      Extract  Starting Pointers
      Extract  Pointers, Cast & Type Punning
  11. Structs
      Extract Basic Structs 
      Extract Typedef
  12. Bit Manipulation
      Extract Basic Bits
      Extract Shifts And Rotates 
  13. Files
     Extract Files
     
    Extract Random Access Files 
  14. Compiling C – Preprocessor, Compiler, Linker
     Extract Compilation & Preprocessor

Also see the companion volume: Applying C

<ASIN:1871962609>

<ASIN:1871962463>

<ASIN:1871962617>

<ASIN:1871962455>

 

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

Banner


Code.Org Distributing $1 Million In CS Leaders Prizes
14/11/2022

This year's Hour of Code will take place as usual during December's Computer Science Education Week. Meanwhile there's a deadline of November 21st for applying for a CS Leaders Prize of $10,000 to&nbs [ ... ]



Fibonacci Day 2022
23/11/2022

Did you know that today is Fibonacci Day? It honors the 12th century Italian mathematician known for the number sequence that is regarded as "nature's secret code". The day is celebrated annually on N [ ... ]


More News

picobook

 



 

Comments




or email your comment to: comments@i-programmer.info

 



Last Updated ( Tuesday, 22 February 2022 )