c - 使用 fwrite() 删除数据

标签 c file-io fwrite

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

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

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/

相关文章:

c - IOCCC 1984/decot.c - 可以在 21 世纪编译吗?

c - 如果散列是唯一的,但散列表中的散列%大小相同,会发生什么?

c# - 高效读取和剪切文件的方法

c - 为什么我的代码无法使用 sprintf 和 fopen 打开新文件?

php - mysql 到 csv 而不使用 mysql 的 INTO OUTFILE

c - 将数据写入二进制文件

c++ - 从 C++ 将 uint8_t* buffer 和 size_t bufferlen 传递给 C 中的 API 函数的最佳方法是什么

c - 关于运行 strtol 后剩下的内容

python - 在python中以 super 用户身份打开文件

c# - 使用 C# 从 RLM 读取许可文件(C++ 到 C# 的翻译)