动态字符缓冲区C.

时间:2012-02-25 14:02:59

标签: c linux malloc buffer

以下是我从文本文件中读取数据的代码的一部分,删除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);

3 个答案:

答案 0 :(得分:3)

不是在单个缓冲区中收集所有文本,而是可以将上面的内容放在一个循环中,并反复调用read()来填充缓冲区。在阅读时处理每个块,并打印出您目前处理过的部分。当你点击文件结尾时(即read()返回0时),停止。

答案 1 :(得分:3)

如果要阅读完整文件,请执行以下操作:

  1. 打开文件
  2. 使用fstat - 请参阅fstat - 获取尺寸
  3. malloc缓冲区,即buffer = malloc(fileStats.st_size);
  4. 阅读文件fread(buffer, fileStats.st_size, 1);
  5. 关闭文件。
  6. 使用缓冲区玩你心中的内容。
  7. 您可能希望在缓冲区大小中添加一个以将空字符放入其中。

答案 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)