I am using a binary file for reading an array of integers, then each even integer x should become 2 * x and each odd integer x should become 3 * x. When I am doing this it always read the 2nd integer (which is 2
). Any idea?
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *f;
f = fopen("inputData.txt", "w+b");
int n = 5;
int i;
for (i = 1; i <= n; ++i) {
fwrite(&i, sizeof(int), 1, f);
}
int x;
fseek(f, 0, SEEK_SET);
while (fread(&x, sizeof(int), 1, f) == 1) {
printf("%d ", x);
if (x % 2 == 0) {
fseek(f, -sizeof(int), SEEK_CUR);
x = x * 2;
fwrite(&x, sizeof(int), 1, f);
} else {
fseek(f, -sizeof(int), SEEK_CUR);
x = 3 * x;
fwrite(&x, sizeof(int), 1, f);
}
}
fclose(f);
}