A program reads one 40-byte record from a binary file opened with mode "r+b", changes one field in memory, and then overwrites the same record in place.
To return to the start of the record it has just read, the program calls fseek with SEEK_CUR and an offset of bytes. That seek also separates the read from the following write, which an update stream requires. If the program instead writes first and then wants to read, it needs either a file-positioning call or a call to between the write and the read.
When it succeeds, fseek returns . On a binary stream, ftell reports the current position as a count of bytes from the start of the file, so with 40-byte records the record with zero-based index 7 starts at byte .
Unlock full course notes by signing up
Diagnosing a misplaced record update
A file inventory.dat holds 20 fixed-length binary records. To replace the record with index 5, a program calls fopen("inventory.dat", "a+b"), then fseek(fp, 5 * (long)sizeof rec, SEEK_SET), which returns 0, then fwrite(&rec, sizeof rec, 1, fp), which returns 1, and finally fclose(fp). Afterwards the file holds 21 records: the new data is the last record, and record 5 is unchanged. Which explanation of this behaviour is correct?
Tracing the file position through a record update
A binary file holds exactly 20 fixed-length records of 48 bytes each, so it is 960 bytes long. On a POSIX system, a program opens it with mode "r+b", so the position starts at byte 0, and buf is a 144-byte array. The program then makes these seven calls in order:
Every call succeeds as far as the file allows. For each call, enter the value ftell(fp) would return immediately after it, in bytes from the start of the file, and the value the call itself returns. Give whole numbers.
Record count, end-relative seek and disk blocks
A sensor archive is a binary file with no header, made of fixed-length records of 100 bytes each, indexed from 0. The file is 25,600 bytes long, and the disk transfers data in 512-byte blocks numbered from 0, with block 0 starting at byte 0 of the file. Find, each as an exact integer:
the number of records in the file;
the offset in bytes to pass to fseek with SEEK_END to reach the start of the record with index 250;
Writing a record beyond the end of a random file
A random-access file of fixed-length 64-byte records currently holds records 0 to 11, so it is 768 bytes long. On a POSIX system, a program opens it with mode "r+b" and stores a new record at zero-based index 30:
Both calls succeed. The program then seeks to the start of record 20 and calls fread(buf, 64, 1, fp).
Give whole numbers for: the new file size in bytes, the number of 64-byte record slots between the old end of file and the new record that were never written, the total size of that gap in bytes, and the value returned by the final fread.