Operating System - Linux
1832973 Members
2178 Online
110048 Solutions
New Discussion

Reading line by line using C

 
SOLVED
Go to solution
Henry Chua
Super Advisor

Reading line by line using C

Hi guys,

Is there a way to write a c program to read a textfile line by line and also field by field seperated by a seperator i.e. like awk.

Best regards
Henry
3 REPLIES 3
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Reading line by line using C

The fgets() function will read until it 1) encounters a linefeed, 2) reaches EOF, or 3) fills the buffer you specify with the 'n' (2nd) parameter. The file pointer is left unchanged so the next call to fgets() will read the next line. Man fgets for details.

To parse a line of text after reading it in with fgets() use strtok() or sscanf(). Man strtok, scanf for details.
If it ain't broke, I can fix that.
Biswajit Tripathy
Honored Contributor

Re: Reading line by line using C

As A Clay Stephenson said, use fgets() followed
by strtok(). Be very careful while using
strtok(), it's a little tricky if you have not
used it before.

Another possible (and simpler) option is
strchr() instead of strtok(). See manpage for
more detail.

- Biswajit
:-)
Henry Chua
Super Advisor

Re: Reading line by line using C

thanks guys, your suggestion works great.!