所以我有一个大文件,一旦达到一定大小,我想完全删除前半部分并将后半部分向下移动,有效地将其缩小一半。这是我的想法:
FILE *fp, *start;
int ch, block_length, filesize;
char c;
//open the file and initialize pointers
fp = fopen(FILEPATH, "rb+");
start = fp;
rewind(start);
//Check the size of the file
fseek(fp, 0, SEEK_END);
filesize = ftell(fp);
if(filesize >= LOG_MAX_FILE_SIZE)
{
//Go to middle of file
fseek(fp, (-1) * LOG_MAX_FILE_SIZE/2, SEEK_END);
//Go forwards until you get a new line character to avoid cutting a line in half
for(;;)
{
//Read char
fread(&ch, 1, 1, fp);
//Advance pointer
fseek(fp, 1, SEEK_CUR);
if( (char)ch == '\n' || ch == EOF)
break;
}
//fp is now after newline char roughly in middle of file
//Loop over bytes and put them at start of file until EOF
for(;;)
{
//Read char
fread(&ch, 1, 1, fp);
//Advance pointer
fseek(fp, 1, SEEK_CUR);
if(ch != EOF)
{
c = (char)ch;
fwrite(&c,1,1,start);
fflush(start);
//Advance start
fseek(start, 1, SEEK_CUR);
}
else
break;
}
//Calculate length of this new file
block_length = ftell(start);
//Go back to start
rewind(start);
//Truncate file to block length
ftruncate(fileno(start), block_length);
}
但是,这似乎在做一些非常非常奇怪的事情(用'f'填充文件,混合行和其中的一些字符等)。有没有人知道我在这段代码中可能做错了什么?预先感谢!