所以我有一個很大的文件,一旦達到一定的大小,我想完全刪除前半部分,並將下半部分向下移動,有效地縮小了一半。繼承人是我在想什麼:用C用第二個替換文件的前半部分並截斷?
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」的文件,線和一些字符混合起來裏面他們,等等)。有沒有人有任何想法,我可能做錯了這個代碼?事先感謝!
它以「rb +」模式打開,正如它在代碼註釋中所述。 – SuperTron 2013-02-15 23:38:49
我不想看到評論的內容:顯示代碼!評論可以說我已經贏得了彩票,但我沒有... – 2013-02-15 23:39:32
好點。代碼現在在那裏。 – SuperTron 2013-02-15 23:42:56