1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
#include <stdio.h>
#define SIZE 20
typedef struct _DATA { // My data structure
int a;
double b;
} DATA;
void view_content() // Method to view file content
{
FILE* fptr;
char what[SIZE];
DATA data;
fptr = fopen("testfile.dat", "rb");
fread(what, SIZE, 1, fptr);
fread(&data, sizeof(data), 1, fptr);
fclose(fptr);
printf("%s\na = %d\nb = %f\n\n", what, data.a, data.b);
}
int main()
{
FILE* fptr;
char what[SIZE] = "random access";
DATA data = { 5, 0.2 };
// This part work ok, It writes the data correctly
fptr = fopen("testfile.dat", "wb");
fwrite(what, SIZE, 1, fptr);
fwrite(&data, sizeof(data), 1, fptr);
fclose(fptr);
view_content();
// This part doesn't update the file
fptr = fopen("testfile.txt", "a+b");
fseek(fptr, SIZE, SEEK_SET); // Positions the file pointer
data.a = 10; // New data assigned to be written
data.b = 9.5;
fwrite(&data, sizeof(data), 1, fptr);
fclose(fptr);
view_content();
return 0;
}
| |