the fgetc function in C should read just on caracter but in this code read more then one caracter .
in this code i test the function fseek to move the cursur and get each time the next caracter using the function fgetc . I apply this on file containe the number from 1 to 19 . but when i try to read the first 1 in the number 11 it read 12 i don't why this happen.
#include <stdio.h>
#include <stdlib.h>
#define BLOCK_SIZE 20
int main() {
int i;
FILE *file;
char buffer[BLOCK_SIZE];
int returnCode;
int value;
// Open or create the binary file for writing
file = fopen("data.bin", "wb");
if (file == NULL) {
perror("Error opening file");
return 1;
}
// Fill the buffer with consecutive values from 0 to 19
for (i = 0; i < BLOCK_SIZE; i++) {
buffer[i] = i;
}
// Write the entire buffer to the file
fwrite(buffer, BLOCK_SIZE, 1, file);
// Close the file
fclose(file);
// Open the file for reading in binary mode
file = fopen("data.bin", "rb");
if (file == NULL) {
perror("Error opening file");
return 1;
}
// Move the file cursor to the 5th byte from the beginning
returnCode = fseek(file, 5, SEEK_SET);
if (returnCode != 0) {
printf("Changement de position impossible\n");
fclose(file);
exit(EXIT_FAILURE);
}
// Read the byte at the current cursor position
value = fgetc(file);
printf("Le 5eme octet allant du debut est %d\n", value);
// Read the next byte after the current cursor position
value = fgetc(file);
printf("L'octet suivant est %d\n", value);
// Move the file cursor 5 bytes forward from the current position
returnCode = fseek(file, 5, SEEK_CUR);
value = fgetc(file);
printf("Octet 5 positions plus loin de la position actuelle est %d\n", value);
// Move the file cursor 5 bytes backward from the end of the file
returnCode = fseek(file, -5, SEEK_END);
value = fgetc(file);
printf("5eme octet à partir de la fin est %d\n", value);
// Close the file
fclose(file);
return 0;
}
this the outuput : this the output of this code
%cif you want the characters themselves.@name.