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/41967289/

相关文章:

c - system() 输出到 char*

file-io - 使用 Groovy 从 Jenkins 主节点访问从节点上的文件

java - 引用文件的工作原理取决于它是否在 Eclipse 中运行

c++ - 是否可以跳过数据文件中的一行?

C 以二进制模式读取文件并写入输出文件

c - Pow 函数返回错误结果

c - C 中的环境变量

c - 如何验证从文件中读取的枚举值?

C++ fwrite 破坏二进制文件

c - 在C中的二进制文件中写入字节0