使用fwrite()删除数据 [英] Using fwrite() deletes data

查看:594
本文介绍了使用fwrite()删除数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了好玩,我写了一个非常简单的文件破坏程序,但令我吃惊的是,损坏的文件比原来的文件大小要小。



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

$ $ $ $ $ $ $ b $ corruptor(char * inputname, int百分比)
{
FILE * input;
FILE *输出;
int文件大小;

char * outputname = append_name(inputname);

//重复文件
cp(outputname,inputname);

//打开输入和输出
input = fopen(inputname,r);
if(input == NULL)
{
printf(Can not open input,errno =%d\\\
,errno);
exit(0);
}
output = fopen(outputname,w +);
if(output == NULL)
{
printf(Can not open output,errno =%d\\\
,errno);
exit(0);
}

//获取输入文件大小
fseek(input,0,SEEK_END);
filesize = ftell(input);

//百分比
int百分比=(文件大小*百分比)/ 100;

srand(time(NULL));

(int i = 0; i <百分比; ++ i)
{
unsigned int r = rand()%filesize;

fseek(output,r,SEEK_SET);
unsigned char corrbyte = rand()%255;
fwrite(& corrbyte,1,sizeof(char),output);

printf(损坏的字节%d \ n,r);
}

fclose(input);
fclose(输出);

$ / code>


解决方案

  output = fopen(outputname,w +); 

删除文件内容,打开文件进行读写操作而不删除内容,使用模式r +。

I wrote a very simple file corruptor for fun, but to my surprise, the "corrupted" file ends up being smaller in size than the original.

Here is the corruption function that is supposed to replace bytes but not to delete them:

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+");

This deletes the contents of the file, To open the file for reading and writing without deleting the contents, use mode "r+".

这篇关于使用fwrite()删除数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆