Reading one line at a time in C

后端 未结 10 872
萌比男神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条回答
  •  萌比男神i
    2020-12-01 13:41

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

    #include 
    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;
    }
    

提交回复
热议问题