Allocation/exo3.c

90 lines
2.0 KiB
C
Raw Normal View History

2024-12-10 14:07:28 +01:00
include <stdio.h>
#include <stdlib.h>
void deplacerPremierOctet(const char *filename) {
FILE *file;
unsigned char first_byte;
long file_size;
unsigned char *buffer;
file = fopen(filename, "r+b");
if (file == NULL) {
perror("Erreur d'ouverture");
exit(EXIT_FAILURE);
}
if (fread(&first_byte, 1, 1, file) != 1) {
perror("Erreur de lecture");
fclose(file);
exit(EXIT_FAILURE);
}
fseek(file, 0, SEEK_END);
if (fwrite(&first_byte, 1, 1, file) != 1) {
perror("Erreur d'écriture");
fclose(file);
exit(EXIT_FAILURE);
}
file_size = ftell(file);
fclose(file);
file = fopen(filename, "r+b");
if (file == NULL) {
perror("Erreur d'ouverture");
exit(EXIT_FAILURE);
}
buffer = (unsigned char *)malloc(file_size - 1);
if (buffer == NULL) {
perror("Erreur d'allocation mémoire");
fclose(file);
exit(EXIT_FAILURE);
}
fseek(file, 1, SEEK_SET);
if (fread(buffer, 1, file_size - 1, file) != file_size - 1) {
perror("Erreur de lecture");
free(buffer);
fclose(file);
exit(EXIT_FAILURE);
}
fclose(file);
file = fopen(filename, "wb");
if (file == NULL) {
perror("Erreur d'ouverture");
free(buffer);
exit(EXIT_FAILURE);
}
if (fwrite(buffer, 1, file_size - 1, file) != file_size - 1) {
perror("Erreur d'écriture");
free(buffer);
fclose(file);
exit(EXIT_FAILURE);
}
if (fwrite(&first_byte, 1, 1, file) != 1) {
perror("Erreur d'écriture");
free(buffer);
fclose(file);
exit(EXIT_FAILURE);
}
free(buffer);
fclose(file);
printf("Modification effectuée.\n");
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <toto.c>\n", argv[0]);
exit(EXIT_FAILURE);
}
deplacerPremierOctet(argv[1]);
return 0;
}