Reading one line at a time in C

后端 未结 10 869
萌比男神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; 
    }
    
    0 讨论(0)
  • 2020-12-01 13:38

    Use fgets to read from the line, and then use getc(...) to chew up the newline or end-of-line to continue reading....here's an example of forever reading a line...

    // Reads 500 characters or 1 line, whichever is shorter
    char c[500], chewup;
    while (true){
        fgets(c, sizeof(c), pFile);
        if (!feof(pFile)){
            chewup = getc(pFile); // To chew up the newline terminator
            // Do something with C
        }else{
            break; // End of File reached...
        }
    }
    
    0 讨论(0)
  • 2020-12-01 13:40

    You can use fscanf instead of fgets. Because fgets fscanf for characters including spaces but while using fscanf you can separately access to data saved in a file.eg there be a file having name class roll.now declare a string and two integers line.

    0 讨论(0)
  • 2020-12-01 13:41

    Use the following program for getting the line by line from a file.

    #include <stdio.h>
    int main ( void )
    {
      char filename[] = "file.txt";
      FILE *file = fopen ( filename, "r" );
    
      if (file != NULL) {
        char line [1000];
        while(fgets(line,sizeof line,file)!= NULL) /* read a line from a file */ {
          fprintf(stdout,"%s",line); //print the file contents on stdout.
        }
    
        fclose(file);
      }
      else {
        perror(filename); //print the error message on stderr.
      }
    
      return 0;
    }
    
    0 讨论(0)
  • 2020-12-01 13:44

    This is more of a comment than a complete answer, but I don't have enough points to comment. :)

    Here's the function prototype for fgets():

    char *fgets(char *restrict s, int n, FILE *restrict stream);
    

    It will read n-1 bytes or up to a newline or eof. For more info see here

    0 讨论(0)
  • 2020-12-01 13:51

    fgets() should be the way to go …

    0 讨论(0)
提交回复
热议问题