Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading one line at a time in C

Tags:

c

file

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?

like image 427
Mahesh Gupta Avatar asked Mar 03 '10 16:03

Mahesh Gupta


4 Answers

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;
}
like image 140
rekha_sri Avatar answered Oct 03 '22 19:10

rekha_sri


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; 
}
like image 30
LukeN Avatar answered Oct 03 '22 17:10

LukeN


If you are coding for a platform that has the GNU C library available, you can use getline():

http://www.gnu.org/s/libc/manual/html_node/Line-Input.html

like image 40
Ant Avatar answered Oct 03 '22 19:10

Ant


The fgets function will read a single line from a file or num characters where num is the second parameter passed to fgets. Are you passing a big enough number to read the line?

For Example

// Reads 500 characters or 1 line, whichever is shorter
char c[500];
fgets(c, 500, pFile);

Vs.

// Reads at most 1 character
char c;
fgets(&c,1,pFile);
like image 35
JaredPar Avatar answered Oct 03 '22 19:10

JaredPar