【发布时间】:2012-02-25 14:02:59
【问题描述】:
下面是我的代码的一部分,用于从文本文件中读取数据、去除 HTML 并仅打印出普通文本。这一切都很好,但我在阅读所有文本文件时遇到了问题。我将如何阅读整个文本文件,了解我可能需要使用 malloc 但不确定如何使用。
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);
【问题讨论】:
-
你必须循环调用
read直到你得到0,跟踪你读过的数量,并将它附加到缓冲区;缓冲区需要根据需要增长,大概是通过realloc。