Question about fgets.

T

Tcc

Hi all,

Assume there are some data in a file "a.txt":

abc def 11<---------------------data in a.txt

is it possible for me to use "fgets" function to get the string "abc", "def"
and "11" individulely?
and How?

if can't, what function can I use in order to solve this problem?

Thanks.
 
M

Mike Wahler

Tcc said:
Hi all,

Assume there are some data in a file "a.txt":

abc def 11<---------------------data in a.txt

is it possible for me to use "fgets" function to get the string "abc", "def"
and "11" individulely?

No. By definition, 'fgets()' reads up to a newline character
or end-of-file (or error occurs), whichever comes first.
and How?

if can't, what function can I use in order to solve this problem?

'fscanf()'

Or use 'fgets()' to read a whole line into a string, then
use 'sscanf()' against that string to extract the individual
strings.

-Mike
 
M

Malcolm

Tcc said:
Assume there are some data in a file "a.txt":

abc def 11<---------------------data in a.txt

is it possible for me to use "fgets" function to get the string "abc", "def"
and "11" individulely?
and How?
fgets() isn't very suitable, since it is designed to read whole lines
terminated by a newline.
if can't, what function can I use in order to solve this problem?
You can use fscanf(), or you can use fgets() to read the whole line, and
then call strtok() to parse the input.
 
D

Dan Pop

In said:
No. By definition, 'fgets()' reads up to a newline character
or end-of-file (or error occurs), whichever comes first.


'fscanf()'

Right, except that it needs to be *carefully* used (otherwise it is
very easy to lose track of your actual position in the input stream).
Or use 'fgets()' to read a whole line into a string, then
use 'sscanf()' against that string to extract the individual
strings.

Doesn't work very well when the number of items on a line is not known
in advance. If it is, reading the whole line with fscanf and parsing it
with sscanf is the simplest solution.

Dan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top