Reputation: 327
basically my problem is that when I use the following program:
#include <stdlib.h>
#include <stdio.h>
#define SIZE 1000
int main() {
FILE *fp;
int r, i;
char fp_string[600] = "/Users/mac/Library/Mobile Documents/com~apple~CloudDocs/College/Program With Persistent Data/Lab 3/num1000.bin";
fp = fopen(fp_string, "rb+");
r = 11;
fseek(fp, 3 * sizeof(int), SEEK_SET);
fwrite(&r, sizeof(int), 1, fp);
fseek(fp, 10 * sizeof(int), SEEK_SET);
fwrite(&r, sizeof(int), 1, fp);
fclose(fp);
return 0;
}
It updates the binary file (which is 1000 integers) with the 3rd and 10th digits to be 11.
But when I do the following:
#include <stdlib.h>
#include <stdio.h>
#define SIZE 1000
int main() {
FILE *fp;
int r, i;
char fp_string[600] = "/Users/mac/Library/Mobile Documents/com~apple~CloudDocs/College/Program With Persistent Data/Lab 3/num1000.bin";
fp = fopen(fp_string, "rb+");
r = 11;
printf("\n\n Before making any changes:\n");
for (i = 0; i < SIZE; i++) {
fseek(fp, i * sizeof(int), SEEK_SET);
fread(&r, sizeof(int), 1, fp);
printf("%d ", r);
}
fseek(fp, 3 * sizeof(int), SEEK_SET);
fwrite(&r, sizeof(int), 1, fp);
fseek(fp, 10 * sizeof(int), SEEK_SET);
fwrite(&r, sizeof(int), 1, fp);
printf("\n\n After making changes:\n");
fseek(fp, 0, SEEK_SET);
for (i = 0; i < SIZE; i++) {
fread(&r, sizeof(int), 1, fp);
printf("%d ", r);
}
fclose(fp);
return 0;
}
It doesn't change anything at all. Just in case you where wondering, to check if the first program worked what I did is:
That way it worked, but the first program doesn't seem to change anything, it shows the exact same numbers again.
#include <stdlib.h>
#include <stdio.h>
#define SIZE 1000
int main() {
FILE *fp;
int r, i;
char fp_string[600] = "/Users/mac/Library/Mobile Documents/com~apple~CloudDocs/College/Program With Persistent Data/Lab 3/num1000.bin";
fp = fopen(fp_string, "rb");
for (i=0;i<SIZE;i++) {
fread(&r, sizeof(int), 1, fp);
printf("%d ", r);
}
fclose(fp);
return 0;
}
Upvotes: 2
Views: 1063
Reputation: 780798
The first for
loop is reading every number in the file into r
before printing them. At the end of the loop, r
contains the last number in the file, and that gets written into the places where you seek.
Either use a different variable in the loop, or put the r = 11;
assignment after the loop.
Upvotes: 3