Topic : Introduction to C Programming
Author : Mkoubaa
Page : << Previous 13  
Go to page :


  
    for (i=1;i<=10; i++)    
    {    
        fread(&r,sizeof(struct rec),1,f);      
        printf("%d\n",r.x);    
    }    
    fclose(f);    
}


In this program, a meaningless record description rec has been used, but you can use any record description you want. You can see that fopen and fclose work exactly as they did for text files.
The new functions here are fread, fwrite and fseek. The fread function takes four parameters: a memory address, the number of bytes to read per block, the number of blocks to read, and the file variable. Thus, the line fread(&r,sizeof(struct rec),1,f); says to read 12 bytes (the size of rec) from the file f (from the current location of the file pointer) into memory address &r. One block of 12 bytes is requested. It would be just as easy to read 100 blocks from disk into an array in memory by changing 1 to 100.
The fwrite function works the same way, but moves the block of bytes from memory to the file. The fseek function moves the file pointer to a byte in the file. Generally, you move the pointer in sizeof(struct rec) increments to keep the pointer at record boundaries. You can use three options when seeking: SEEK_SET, SEEK_CUR and SEEK_END. SEEK_SET moves the pointer x bytes down from the beginning of the file (from byte 0 in the file). SEEK_CUR moves the pointer x bytes down from the current pointer position. SEEK_END moves the pointer from the end of the file (so you must use negative offsets with this option).
Several different options appear in the code above. In particular, note the section where the file is opened with r+ mode. This opens the file for reading and writing, which allows records to be changed. The code seeks to a record, reads it, and changes a field; it then seeks back because the read displaced the pointer, and writes the change back.

mkoubaa@ix.urz.uni-heidelberg.de

Page : << Previous 13