3. Binary files
•Basic IO examples with binary files (using ftell):
Systems Architecture - 8. Working with files in C 20
#include <stdio.h>
#include <stdlib.h>
#define MAX_STR 255
int main() {
FILE *fp = fopen("file2.bin", "rb");
if (!fp) {
perror("An error occurred opening the file");
return 1;
}
printf("The content of the binary file is:\n");
char record[MAX_STR];
int file_pos = ftell(fp);
printf("[file position at the beginning is: %d]\n", file_pos);
while (fread(&record, sizeof(record), 1, fp) == 1) {
file_pos = ftell(fp);
printf("%s [file position is: %d]\n", record, file_pos);
}
printf("[file position at the end is: %d]\n", file_pos);
fclose(fp);
return 0;
}
The content of the binary file is:
[file position at the beginning is: 0]
This is line 1 [file position is: 255]
This is line 2 [file position is: 510]
This is line 3 [file position is: 765]
This is line 4 [file position is: 1020]
This is line 5 [file position is: 1275]
This is line 6 [file position is: 1530]
This is line 7 [file position is: 1785]
This is line 8 [file position is: 2040]
This is line 9 [file position is: 2295]
This is line 10 [file position is: 2550]
[file position at the end is: 2550]