在C语言中一次读取多行

问题描述 投票:0回答:2

所以我有一个巨大的文件,大约1GB。每一行都算作一个查询,一旦我读取了这些查询,我就把它们插入一个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';
        }

     }

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

c file
2个回答
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); }

0
投票

OP的代码试图将所有文件的行数读入一个缓冲区--在一个相当大的范围内 低效率.

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

如果还想把整个文件读到一个缓冲区中,找到它的长度(最好是通过某些 fstat() 唤作),分配,然后用1 fread(). 另一种Linux方式是 mmap. 然后对缓冲区进行行处理。


漏洞。line[strlen(line)-1 == '\n'] 是UB应该读取的第一个字符竟然是一个字。空字.

© www.soinside.com 2019 - 2024. All rights reserved.