对不起,我误读了这个问题。
您将需要考虑几件事。是的,你需要一个缓冲区,但如果你的行大于缓冲区,你也有句柄。所以你需要两个缓冲区,一个用来读入,另一个用来组装整行。虽然可以在一个缓冲区中完成,但它似乎过于复杂。
我的 C 很生锈,但这似乎有效。它需要错误处理,我确信它与您的编码风格不匹配,但我的一次完成测试似乎有效。读取缓冲区异常小,以证明行大于缓冲区的情况 - 在现实世界中,您的读取缓冲区会大得多。
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
int findchar(char*, int, char);
int main()
{
size_t dataIn = open("myfile.txt", O_RDONLY);
size_t gtOut = open("greaterthan.txt", O_CREAT | O_WRONLY);
size_t coOut = open("colon.txt", O_CREAT | O_WRONLY);
char buffer[12];
int iReadCnt;
char* lineBuffer = NULL;
int lineBufferSize = 0;
// read input file until no more input
while (iReadCnt = read(dataIn, buffer, sizeof(buffer)))
{
int x;
int n;
char* b;
// add buffer to dynamic line buffer
n = lineBufferSize + iReadCnt;
b = malloc(n);
memcpy(b, lineBuffer, lineBufferSize);
memcpy(&b[lineBufferSize], buffer, iReadCnt);
// free old buffer if exists
if (lineBuffer)
{
free(lineBuffer);
}
lineBufferSize = n;
lineBuffer = b;
// look for end of line
x = findchar(lineBuffer, lineBufferSize, '\n');
if (x >= 0)
{
int gtPos;
int coPos;
int n;
char* b;
// look for gt
gtPos = findchar(lineBuffer, x, '>');
if (gtPos >= 0)
{
write(gtOut, lineBuffer, x + 1);
}
// look for colon
coPos = findchar(lineBuffer, x, ':');
if (coPos >= 0)
{
write(coOut, lineBuffer, x + 1);
}
// remove line from buffer
n = lineBufferSize - (x + 1);
b = malloc(n);
memcpy(b, &lineBuffer[x + 1], n);
free(lineBuffer);
lineBufferSize = n;
lineBuffer = b;
}
}
// close files
close(dataIn);
close(gtOut);
close(coOut);
exit(0);
}
// simple function to find a character in a buffer
int findchar(char* buffer, int len, char c)
{
int i;
for (i = 0; i < len; ++i)
{
if (buffer[i] == c)
{
return i;
}
}
return -1;
}