使用 fwrite() 删除数据

2023-12-15

我为了好玩写了一个非常简单的文件损坏器,但令我惊讶的是,“损坏”的文件最终比原始文件小。

这是应该替换字节但不删除它们的损坏函数:

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+”。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 fwrite() 删除数据 的相关文章

随机推荐