RingDotNetfor Ring

Random access and file locks

A file of records with the same size can be used like a table: the program goes straight to record 3, changes it in place and adds one at the end. This lesson uses FileStream with Seek, Write, SetLength and FileShare, and shows how a lock keeps two writers away from one file.

What you will learn#

The tutorial Binary files wrote and read a file from the first byte to the last. This lesson jumps to a place in the file.

The program#

samples/UsingDotNet/tutorials/ch05_random_access.ring
# random access files - FileStream: records of a fixed size, Seek, changing one record in place, SetLength and locking a file with FileShare
load "dotnet.ring"

using {
	"System"
	"System.IO"
	"System.Text"
}

nSize = 20                        # every record has 20 bytes: the name in 12, the quantity in 4, and 4 spaces

func main

	oPath = new Path()
	cFolder = oPath.Combine([ oPath.GetTempPath(), "ringdotnet-records-" + oPath.GetRandomFileName() ])
	new Directory().CreateDirectory(cFolder)
	cFile = cFolder + "/stock.dat"

	# A text file is read from the first byte to the last. A file of RECORDS with the same size can be used like a table: record number n
	# starts at the byte n * size, so the program goes to it with Seek, without reading the records before it.

	# 1. Write five records. The FileStream is opened with a mode (Create: a new empty file) and an access (what the program may do).
	oStream = openFile(cFile,"Create","ReadWrite","None")
	for aItem in [ ["Tea",40], ["Coffee",25], ["Sugar",100], ["Milk",8], ["Honey",12] ]
		writeRecord(oStream,aItem[1],aItem[2])
	next
	oStream.Flush(NULL)                               # push what is in the memory of the program to the file
	? "1. five records written, the file has " + oStream.Length + " bytes (5 x " + nSize + ")"

	# 2. Read record 3 without reading the first two: Seek(offset, origin) moves the position; "Begin" counts from the start of the file
	? nl + "2. record 3: " + showRecord(readRecord(oStream,3))
	? "   the position is now " + oStream.Position + ", right after that record"

	# 3. Change one record IN PLACE: seek to it and write the new bytes over the old ones. The other records are not touched.
	writeRecordAt(oStream,3,"Sugar",90)
	? nl + "3. after selling 10 of the sugar:"
	for i = 1 to 5
		? "   " + i + ". " + showRecord(readRecord(oStream,i))
	next

	# 4. Add a record at the end: seek to the end of the file (Length) and write
	writeRecordAt(oStream,6,"Jam",30)
	? nl + "4. a sixth record was added: the file has " + oStream.Length + " bytes, " + (oStream.Length / nSize) + " records"

	# 5. SetLength cuts the file (or makes it longer: the new bytes are zero). Three records stay.
	oStream.SetLength(3 * nSize)
	? nl + "5. after SetLength(3 * " + nSize + "): " + (oStream.Length / nSize) + " records, the last is " + showRecord(readRecord(oStream,3))
	oStream.Dispose()

	# 6. Locking. FileShare says what OTHER programs (and other FileStreams of this program) may do while the file is open. "None": nobody.
	#    A second open raises an IOException: the file is in use. This is how a program makes sure that only one writer works on a file.
	oFirst = openFile(cFile,"Open","ReadWrite","None")
	? nl + "6. the file is open with FileShare.None:"
	? "   a second open for reading: " + tryOpen(cFile,"Read","Read")
	oFirst.Dispose()
	? "   after the first stream was closed: " + tryOpen(cFile,"Read","Read")

	# 7. "Read" shares reading: many readers are fine at the same time, and a writer is refused
	oReader = openFile(cFile,"Open","Read","Read")
	? nl + "7. the file is open for reading with FileShare.Read:"
	? "   another reader: " + tryOpen(cFile,"Read","Read")
	? "   a writer:       " + tryOpen(cFile,"ReadWrite","Read")
	oReader.Dispose()

	new Directory().Delete([ :path = cFolder, :recursive = True ])

# a FileStream: the path, the mode, the access and the share
func openFile cFile,cMode,cAccess,cShare

	return (new FileStream).@New([ :path = cFile, :mode = cMode, :access = cAccess, :share = cShare ])

# a record: the name to 12 characters (spaces on the right), the quantity to 4 digits (zeros on the left), and 4 spaces
func makeRecord cName,nQuantity

	return left(cName + copy(" ",12),12) + right("0000" + nQuantity,4) + "    "

func writeRecord oStream,cName,nQuantity

	cRecord = makeRecord(cName,nQuantity)
	oStream.Write(cRecord,0,nSize)

# record number n (from 1): go to its place and write
func writeRecordAt oStream,n,cName,nQuantity

	oStream.Seek((n - 1) * nSize,"Begin")
	writeRecord(oStream,cName,nQuantity)

func readRecord oStream,n

	oStream.Seek((n - 1) * nSize,"Begin")
	oBuffer = dnBuffer(nSize)                              # a .NET byte[] that Read fills
	nRead = oStream.Read(oBuffer,0,nSize)
	return dnBufferBytes(oBuffer,nRead)

func showRecord cRecord

	return trim(left(cRecord,12)) + ", quantity " + (0 + substr(cRecord,13,4))

# try to open a file; the answer is "ok" or the kind of the error
func tryOpen cFile,cAccess,cShare

	try
		oStream = openFile(cFile,"Open",cAccess,cShare)
		oStream.Dispose()
		return "ok"
	catch
		return errorKind(cCatchError)
	done

func errorKind cMessage

	cText = trim(cMessage)
	nStart = substr(cText,"DotNet Error: ")
	if nStart > 0
		cText = substr(cText,nStart + 14)
	ok
	nEnd = substr(cText,":")
	if nEnd > 0
		cText = left(cText,nEnd - 1)
	ok
	return cText
Output
1. five records written, the file has 100 bytes (5 x 20)

2. record 3: Sugar, quantity 100
   the position is now 60, right after that record

3. after selling 10 of the sugar:
   1. Tea, quantity 40
   2. Coffee, quantity 25
   3. Sugar, quantity 90
   4. Milk, quantity 8
   5. Honey, quantity 12

4. a sixth record was added: the file has 120 bytes, 6 records

5. after SetLength(3 * 20): 3 records, the last is Sugar, quantity 90

6. the file is open with FileShare.None:
   a second open for reading: System.IO.IOException
   after the first stream was closed: ok

7. the file is open for reading with FileShare.Read:
   another reader: ok
   a writer:       System.IO.IOException
Note

This program uses a few generic functions (dnNew, dnBuffer) where a class cannot be used. The lesson The generic functions explains them.

How it works#

Records of a fixed size#

Every record of the file has 20 bytes: the name in 12 characters (spaces fill the rest), the quantity in 4 digits (zeros in front) and 4 spaces. With a fixed size, record number n (counted from 1) starts at byte (n - 1) * 20. The program needs no index and does not read the records before it. Real formats of this kind use binary numbers (the tutorial Binary files); text fields are used here so that the file can be read by eye.

Opening a FileStream#

dnNew("FileStream",[ :path = ..., :mode = "Create", :access = "ReadWrite", :share = "None" ]) has three important values. The mode says what happens when the file exists: Create makes a new empty file, Open opens an existing one, OpenOrCreate does either, Append writes at the end. The access says what this stream may do (Read, Write, ReadWrite). The share says what others may do while the stream is open.

Seek and Position#

Seek(offset, "Begin") moves the position to a byte counted from the start ("Current" and "End" are the other origins). Position is where the next read or write happens: after reading record 3 it is 60, right after the record. Write(text, 0, count) writes count bytes of a text. Read(buffer, 0, count) reads them into a byte buffer (dnBuffer(count)), a .NET array that Ring holds, and gives the number of bytes it wrote; dnBufferBytes(buffer, n) copies them into a Ring text (the tutorial Binary files).

In place#

To change a record the program seeks to it and writes 20 new bytes over the old ones. Nothing else moves, so changing one record is as fast in a big file as in a small one. This only works because the new record has exactly the same size. To add a record the program seeks to the end (n = 6, the byte 100) and writes there; the file becomes longer.

Flush and SetLength#

A stream keeps some bytes in memory before it gives them to the system. Flush writes them at once; Dispose flushes and closes. SetLength cuts the file (the program keeps three records) or makes it longer (the new bytes are zeros).

Locks#

FileShare.None says that nobody else may open the file. A second open, from another program or from another stream of the same program, raises System.IO.IOException, because the file is in use. Closing the first stream (Dispose) releases the lock. FileShare.Read lets other streams read but not write: two readers are fine, a writer is refused. A program that updates a data file opens it with None, so two copies of the program cannot damage it by writing at the same time.

Note

On Linux and macOS .NET uses advisory locks: they work between programs that use .NET, but another program can still open the file. Use a lock file or a database when the other programs are not yours.

What you learned#

Exercises#

  1. Write findRecord(oStream, cName) that reads the records one by one until it finds the name.
  2. Add a function deleteRecord(n) that copies the last record over record n and cuts the file by one record.
  3. Make the record size 24 and add a price of 8 characters, and write a program that converts the old file.
  4. Open the file with FileShare.None in one program and try to open it in a second program (the tutorial Two programs talking).

Next#

Copying a big file with progress

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.