以下是我从文本文件中读取数据的代码的一部分,删除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);
答案 0 :(得分:3)
不是在单个缓冲区中收集所有文本,而是可以将上面的内容放在一个循环中,并反复调用read()
来填充缓冲区。在阅读时处理每个块,并打印出您目前处理过的部分。当你点击文件结尾时(即read()
返回0时),停止。
答案 1 :(得分:3)
如果要阅读完整文件,请执行以下操作:
fstat
- 请参阅fstat - 获取尺寸malloc
缓冲区,即buffer = malloc(fileStats.st_size);
fread(buffer, fileStats.st_size, 1);
您可能希望在缓冲区大小中添加一个以将空字符放入其中。
答案 2 :(得分:2)
更有效的方法是使用mmap()调用将文件直接映射到内存中:
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
struct stat statbuf;
stat("data.txt", &statbuf);
size_t len = stat.st_size;
int fd = open("data.txt",O_RDONLY);
char *buf = mmap(NULL, len, PROT_READ, MAP_PRIVATE,fd, 0);
for( i=0; i< len; i++ ) {
// do your own thing here
}
munmap(buf,len);
close(fd);
如果文件长度超过2GB,则使用mmap2()调用 - 您必须调整页面大小,因为最后一个参数位于页面中(通常为4k)