下面是我的代码的一部分,用于从文本文件中读取数据,去除HTML并打印出正常文本。这一切工作膨胀,但我在阅读所有的文本文件有问题。我如何阅读整个文本文件,明白我可能需要使用malloc,但我不确定如何操作。动态char缓冲区C
int i, nRead, fd;
int source;
char buf[1024];
int idx = 0;
int opened = 0;
if((fd = open("data.txt", O_RDONLY)) == -1)
{
printf("Cannot open the file");
}
else
{
nRead = read(fd, buf, 1024);
printf("Original String ");
for(i=0; i<nRead; i++)
{
printf("%c", buf[i]);
}
printf("\nReplaced String ");
for(i=0; i<nRead; i++)
{
if(buf[i]=='<') {
opened = 1;
} else if (buf[i] == '>') {
opened = 0;
} else if (!opened) {
buf[idx++] = buf[i];
}
//printf("%c", buf[i]);
}
}
buf[idx] = '\0';
printf("%s\n", buf);
close(source);
您必须循环读取调用,直到获得0,跟踪您读取的数量并将其附加到缓冲区;缓冲区需要根据需要增长,大概是通过'realloc'。 – 2012-02-25 14:05:08