10.5 Reading From and Writing To a File

Once you have opened a file, you can read from it or write to it by 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 = _lread(hFile, buffer, 512);
    _lclose(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 _lclose function closes the file immediately after it has been read.

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) {
    _lwrite(hFile, buffer, count);
    _lclose(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.