LearnFrenzy
Sign in Take a free test

C Input / Output · Input/Output Programs · Question 6

Update one record in a binary file in place in C Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

Store account balances as binary records, then change the balance of the second record in place (seek, read, seek back, write) and list all records.

Solution
main.c
#include <stdio.h>

struct account {
    int id;
    double balance;
};

int main(void) {
    struct account list[] = {{1, 500.0}, {2, 1200.0}, {3, 50.0}};
    FILE *fp = tmpfile();
    if (fp == NULL)
        return 1;
    fwrite(list, sizeof list[0], 3, fp);

    struct account a;
    long pos = 1L * (long) sizeof a;                 /* record index 1 */
    fseek(fp, pos, SEEK_SET);
    fread(&a, sizeof a, 1, fp);
    a.balance += 300.0;                              /* deposit */
    fseek(fp, pos, SEEK_SET);                        /* required between read and write */
    fwrite(&a, sizeof a, 1, fp);

    rewind(fp);
    while (fread(&a, sizeof a, 1, fp) == 1)
        printf("%d: %.2f\n", a.id, a.balance);
    fclose(fp);
    return 0;
}

Output Verified by compiling and running

1: 500.00
2: 1500.00
3: 50.00

Fixed-size binary records allow direct access. The second fseek both moves back to the record and satisfies the rule that a read must not be followed by a write without a positioning call.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links