之前一朋友说起这个需求,还发了篇文章过来,里面不少实现的办法,最后测试结论是sed,awk的最快?!
我感觉自己能够写得更好,受不了这家伙的激将法,更多时候不是实现不实现的问题,而是效果问题。昨晚忍不住动手自己写了一个。
测试了几次,正确了(说不定还有BUG),应该能够比sed,awk那些快,文章上的一些代码不用跑看看就知道结果了,也可以改成单个文件处理,还能再优化,优化方式具体查我之前发的文章。
// 可以适当调整这个缓冲大小
#define BUFFER_SIZE 0x400
int remove_file_line(HANDLE hfile0, HANDLE hfile1, unsigned int index)
{
unsigned char buffer[BUFFER_SIZE];
unsigned int position = 0;
unsigned int start = 0;
DWORD numberofbytes;
unsigned int i;
unsigned int l;
while (index > 0 && ReadFile(hfile0, buffer + position, BUFFER_SIZE - position, &numberofbytes, NULL) && numberofbytes > 0)
{
numberofbytes += position;
while (position < numberofbytes)
{
if (buffer[position] == '\n')
{
start = position + 1;
index--;
if (index == 0)
{
position++;
break;
}
}
position++;
}
if (index == 0)
{
l = numberofbytes;
if (start > 0)
{
WriteFile(hfile1, buffer, start, &numberofbytes, NULL);
start = 0;
}
i = 0;
while (position < l)
{
buffer[i++] = buffer[position++];
}
position = i;
}
else
{
if (start > 0)
{
WriteFile(hfile1, buffer, start, &numberofbytes, NULL);
i = 0;
while (start < position)
{
buffer[i++] = buffer[start++];
}
start = 0;
position = i;
}
else
{
if (position == BUFFER_SIZE)
{
WriteFile(hfile1, buffer, position, &numberofbytes, NULL);
position = 0;
}
}
}
}
if (index == 0)
{
while (ReadFile(hfile0, buffer + position, BUFFER_SIZE - position, &numberofbytes, NULL) && numberofbytes > 0)
{
numberofbytes += position;
position = 0;
while (position < numberofbytes && buffer[position] != '\n')
{
position++;
}
if (position < numberofbytes)
{
position++;
if (position < numberofbytes)
{
WriteFile(hfile1, buffer + position, numberofbytes - position, &numberofbytes, NULL);
}
position = 0;
break;
}
else
{
position = 0;
}
}
if (position > 0)
{
while (start < position && buffer[start] != '\n')
{
start++;
}
if (start < position)
{
start++;
if (start < position)
{
WriteFile(hfile1, buffer + start, position - start, &numberofbytes, NULL);
}
}
}
while (ReadFile(hfile0, buffer, BUFFER_SIZE, &numberofbytes, NULL) && numberofbytes > 0)
{
WriteFile(hfile1, buffer, numberofbytes, &numberofbytes, NULL);
}
}
else
{
if (position > 0)
{
WriteFile(hfile1, buffer, position, &numberofbytes, NULL);
//position = 0;
}
}
return(index);
}