Reading From and Writing To Files

Once you have opened a file, you can read from it or write to it using low-level, C run-time functions. The following example opens the FILE.TXT file for reading and then reads 512 bytes from it:

char buffer[512];

int count;

.

.

.

hFile = OpenFile("FILE.TXT", &OfStruct, OF_READ);

if(hFile >= 0) {

count = read(hFile, buffer, 512);

close(hFile);

}

In this example, the file handle is checked before bytes are read from the file. OpenFile returns –1 if the file could not be found or opened. The close function closes the file immediately after reading.

The following example opens the FILE.TMP file for writing and then writes bytes from the character-array buffer:

hFile = OpenFile("FILE.TMP", &OfStruct, OF_WRITE);

if(hFile >= 0) {

write(hFile, buffer, count);

close(hFile);

}

You should always close floppy-disk files after reading or writing. This is to prevent problems if you remove the current disk while working with another application. You can always reopen a disk file by using the OF_REOPEN option.