为了好玩,我编写了一个非常简单的文件损坏程序,但令我惊讶的是,“损坏的”文件最终比原始文件小。
这是应该替换字节但不删除它们的损坏函数:
void
corruptor(char *inputname, int percent)
{
FILE *input;
FILE *output;
int filesize;
char *outputname = append_name(inputname);
// Duplicate file
cp(outputname, inputname);
// Open input and output
input = fopen(inputname, "r");
if (input == NULL)
{
printf("Can't open input, errno = %d\n", errno);
exit(0);
}
output = fopen(outputname, "w+");
if (output == NULL)
{
printf("Can't open output, errno = %d\n", errno);
exit(0);
}
// Get the input file size
fseek(input, 0, SEEK_END);
filesize = ftell(input);
// Percentage
int percentage = (filesize * percent) / 100;
srand(time(NULL));
for (int i = 0; i < percentage; ++i)
{
unsigned int r = rand() % filesize;
fseek(output, r, SEEK_SET);
unsigned char corrbyte = rand() % 255;
fwrite(&corrbyte, 1, sizeof(char), output);
printf("Corrupted byte %d\n", r);
}
fclose(input);
fclose(output);
}
最佳答案
output = fopen(outputname, "w+");
这会删除文件的内容,要打开文件进行读写而不删除内容,请使用模式“r+”。
关于c - 使用 fwrite() 删除数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41967058/