使用fwrite()删除数据 [英] Using fwrite() deletes data
问题描述
应该替换字节,但不删除它们的腐败函数:
$ $ $ $ $ $ $ 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屋!