C 使用fwrite()删除数据

C 使用fwrite()删除数据,c,file-io,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, in

为了好玩,我写了一个非常简单的文件腐蚀程序,但令我惊讶的是,“被破坏”的文件最终比原来的文件小

下面是应该替换字节但不删除字节的损坏函数:

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);
}
void
腐蚀器(字符*输入名称,整数百分比)
{
文件*输入;
文件*输出;
int文件大小;
char*outputname=append\u name(inputname);
//重复文件
cp(outputname,inputname);
//开放输入和输出
输入=fopen(输入名称,“r”);
如果(输入==NULL)
{
printf(“无法打开输入,错误号=%d\n”,错误号);
出口(0);
}
output=fopen(outputname,“w+”);
if(输出==NULL)
{
printf(“无法打开输出,错误号=%d\n”,错误号);
出口(0);
}
//获取输入文件的大小
fseek(输入,0,搜索结束);
filesize=ftell(输入);
//百分比
整数百分比=(文件大小*百分比)/100;
srand(时间(空));
对于(int i=0;i

这将删除文件的内容,若要打开文件进行读写而不删除内容,请使用模式“r+”

man fopen
:w+打开进行读写。如果文件不存在,则创建该文件,否则将截断该文件。流位于文件的开头。此外,C11标准草案n1570:w+截断为零长度或为updateThanks@EOF创建文本文件,但w也截断文件输出文件(初始大小为0)将仅与您使用的最大随机位置一样大。我不理解您的意思@weathervane输出文件以大小0开始,因为您刚刚创建了它。该名称的任何早期文件都将被销毁。除非写入的文件位置等于输入文件的长度,否则输出文件将更小。但如果不这样做,则选择随机位置写入输出文件。因此,这将是最大的。MSVC“w+”打开一个空文件进行读写。如果文件存在,则其内容将被销毁。您已修复该文件。谢谢@immibis
output = fopen(outputname, "w+");