繁体   English   中英

在 C 中一次读取多行

[英]Reading multiple lines at once in C

所以我有一个大约 1 GB 的大文件。 每一行都算作一个查询,一旦我阅读了这些查询,我就会将它们插入到 trie 中。 现在我通过逐行读取文本文件一次读取一个查询。行的长度因行而异。 现在我想读取多个查询,因此一次读取多行但我被卡住了。 有什么帮助吗? 该代码显示了我如何从文件中逐行读取。

fp=fopen("test.txt","r");
    if(!fp)
    {
      perror("Couldn't open the file");
      exit(1);
     }
   char chunk[1000];
   size_t len= sizeof(chunk);
   char *line = (char *)malloc(len);
   if(line == NULL){
    perror("Unable to allocate memory for the line buffer");
    exit(1);
   }
   line[0]='\0';
   while(fgets(chunk,sizeof(chunk),fp) != NULL){
        if(len - strlen(line) < sizeof(chunk)){
            len *= 2;
            if((line = realloc(line,len)) == NULL){
                perror("Unable to reallocate memory for the line buffer.");
                exit(1);
             }
        }
        strcat(line,chunk);
        if(line[strlen(line)-1 == '\n']){
            printf("%s\n",line);
            insert(root,line);

            line[0]='\0';
        }

     }

我曾想过要数一下我读了多少行,但我不确定。 似乎解决方案与使用缓冲区大小有关。

我不确定是否理解这个问题,但你可以用这种方式读写而不是 fgets:

   int fd, lung; /* fd, n read bytes */
   char buf[N]; /* how to save data */
   /* open file */
   if ( (fd = open(“s.c”, O_RDONLY)) == -1)
   { perror(“s.c”); exit(EXIT_FAILURE); }
   /* open file OK */
   while ((lung = read(fd,buf,N))>0){
      …
   }   
   if ( lung == -1)
   { perror(“s.c: read”); exit(EXIT_FAILURE); }

OP 的代码试图以相当低效的方式将文件的所有行读入 1 个缓冲区。

通常这对于 1 GByte 数量级的文件是不明智的,最好一次操作几行(或 1 行)。

如果仍然想将整个文件读入缓冲区,请找到它的长度(最好通过诸如 call 之类的fstat() ),分配然后使用 1 fread() 另一种 Linux 方式是mmap 然后处理行的缓冲区。


漏洞利用: line[strlen(line)-1 == '\n']是 UB,如果读取的第一个字符出人意料地是null 字符

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM