Created
April 11, 2023 05:43
-
-
Save simonesestito/5e47df4e6efe4f081304514fff6ae324 to your computer and use it in GitHub Desktop.
Flip an amount of bytes in a file, randomly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <time.h> | |
#include <unistd.h> | |
#include <sys/stat.h> | |
#include <sys/types.h> | |
#define NUMBER_BYTES_TO_FLIP 10 | |
//#define FLIP_PROBABILITY 0.0001 | |
off_t getFileSize(const char *filename) { | |
struct stat sb; | |
if (stat(filename, &sb) == -1) { | |
perror("stat"); | |
return -1; | |
} | |
return sb.st_size; | |
} | |
int main(int argc, char *argv[]) { | |
if (argc != 2) { | |
printf("Uso: %s <file>\n", argv[0]); | |
return 1; | |
} | |
// Apri il file di input in modalità lettura binaria | |
FILE *input_file = fopen(argv[1], "rb"); | |
if (input_file == NULL) { | |
fprintf(stderr, "Errore nell'aprire il file di input!\n"); | |
return 1; | |
} | |
// Apri il file di output in modalità scrittura binaria | |
FILE *output_file = fopen("out.bin", "wb"); | |
if (output_file == NULL) { | |
fprintf(stderr, "Errore nell'aprire il file di output!\n"); | |
fclose(input_file); | |
return 1; | |
} | |
// Inizializza il generatore di numeri casuali | |
srand(time(NULL)); | |
#ifdef FLIP_PROBABILITY | |
double flipProbability = (FLIP_PROBABILITY); | |
#else | |
double flipProbability = (NUMBER_BYTES_TO_FLIP) / getFileSize(argv[1]); | |
#endif | |
unsigned long long int changedBytes = 0; | |
// Leggi un byte alla volta dal file di input e scrivilo sul file di output con la probabilità indicata | |
int byte; | |
while ((byte = fgetc(input_file)) != EOF) { | |
if ((double)rand() / RAND_MAX < flipProbability) { | |
byte = byte ^ 0xFF; // flip | |
changedBytes++; | |
} | |
fputc(byte, output_file); | |
} | |
printf("%llu bytes changed\n", changedBytes); | |
// Chiudi i file | |
fclose(input_file); | |
fclose(output_file); | |
printf("Changed version is 'out.bin'\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment