Reading one line at a time in C

后端 未结 10 873
萌比男神i
萌比男神i 2020-12-01 13:01

Which method can be used to read one line at a time from a file in C?

I am using the fgets function, but it\'s not working. It\'s reading the space

10条回答
  •  隐瞒了意图╮
    2020-12-01 13:34

    This should work, when you can't use fgets() for some reason.

    int readline(FILE *f, char *buffer, size_t len)
    {
       char c; 
       int i;
    
       memset(buffer, 0, len);
    
       for (i = 0; i < len; i++)
       {   
          int c = fgetc(f); 
    
          if (!feof(f)) 
          {   
             if (c == '\r')
                buffer[i] = 0;
             else if (c == '\n')
             {   
                buffer[i] = 0;
    
                return i+1;
             }   
             else
                buffer[i] = c; 
          }   
          else
          {   
             //fprintf(stderr, "read_line(): recv returned %d\n", c);
             return -1; 
          }   
       }   
    
       return -1; 
    }
    

提交回复
热议问题