用C读取300MB文本文件

时间:2012-02-05 06:23:18

标签: c file-io

在C中读取文本文件(最大大小:300 MB)的最佳方法是什么?我想在文本文件中搜索特定模式。此外,我必须访问所有文本字符。

3 个答案:

答案 0 :(得分:4)

我建议将mmap文件放入进程空间,并将文件视为纯文本字符串。这样可以避免任何与malloc内存分配,fread等有关的复杂情况,并且操作系统将根据需要处理任何数据分页。

本手册有一个代码示例 - 要点如下......

 int fd;
 struct stat sb;
 int filesize;
 char *filetext;
 fd = open("/path/to/my/300mb/file", O_RDONLY);
 if (fd == -1)
     handle_error("open");

 if (fstat(fd, &sb) == -1) /* To obtain file size */
     handle_error("fstat");
 filesize = sb.st_size;

 filetext = mmap(NULL, filesize, PROT_READ,MAP_PRIVATE, fd, 0);
 if (filetext == MAP_FAILED)
     handle_error("mmap");

  /* you now have the file mapped into memory with
     filetext[0] as the first byte and
     filetext[filesize-1] as the last byte
   */

  /* use the file content as a char* text string.... */
  while (....) do what ever needed

  /* release the file when done */
  munmap(filetext,filesize); 
  close(fd);

答案 1 :(得分:3)

如果你有相对无限的内存(>>> 300MB),请使用fread()将整个文件读入内存并使用GNU regex库(http://www.gnu.org/software/libc/manual/html_node /Regular-Expressions.html)。

答案 2 :(得分:0)

我建议使用fread()

fread()为您提供与fgetc()一样多的控制权,并且具有能够在单个I / O操作中读取多个字符的优点。事实上,在内存允许的情况下,您可以将整个文件读入数组并在内存中完成所有处理。这具有显着的性能优势。