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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!