使用fwrite()删除数据

时间:2017-01-31 20:53:25

标签: c file-io fwrite

我写了一个非常简单的文件corruptor以获得乐趣,但令我惊讶的是,“损坏的”文件的大小最终比原始文件小。

这是腐败函数,它应该替换字节但不删除它们:

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);
}

1 个答案:

答案 0 :(得分:0)

output = fopen(outputname, "w+");

删除文件内容。要打开文件进行读写而不删除内容,请使用模式&#34; r +&#34;。