Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
691 views
in Technique[技术] by (71.8m points)

file - Reading one line at a time in C

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 separated token only.

What to do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...