动态char缓冲区C
问题描述:
下面是我的代码的一部分,用于从文本文件中读取数据,去除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);
答
如果你想阅读完整的文件执行以下操作:
- 打开文件
- 使用
fstat
- 见fstat - 让大小 -
malloc
缓冲区即buffer = malloc(fileStats.st_size);
- 阅读文件
fread(buffer, fileStats.st_size, 1);
- 关闭文件。
- 玩你的心中的缓冲区内容。
您可能希望添加一个缓冲区大小以将空字符放入其中。
答
而是收集在一个缓冲区中的所有文本,你可以只是把上面的循环,并呼吁read()
反复填充缓冲区。在读取它时处理每个块,并打印出到目前为止处理过的部分。当你点击文件结束时(即当read()
返回0时)停止。
答
更有效的将是使用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)
您必须循环读取调用,直到获得0,跟踪您读取的数量并将其附加到缓冲区;缓冲区需要根据需要增长,大概是通过'realloc'。 – 2012-02-25 14:05:08