rohit said:
Hi All,
I am new to C language.I want to read integers from a text file and
want to do some operation in the main program.To be more specific I
need to multiply each of these integers with another set of integers
stored in an array.It would be a great help if you could provide some
code for it.I tried the function fscanf but by that I am able to read
only the first integer of the text file.Please help me.
Since the integer values are represented in text you need to, in
essence, read each value as a sequence of characters and then convert
the sequence to the value it represents, before storing away your
value. You will need to do this for every integer represented in your
file.
The fscanf function will do the reading and the conversion in one call
for you, but can be a bit difficult to use. In particular the sequence
of characters that fscanf reads from the file must match what it is
expecting from it's format string. The function can fail if it
encounters unexpected characters (like say an alphabet). You can (and
should) check the return value of fscanf after every call to it, before
proceeding.
Another method is to read in a line of text (one or more characters
terminated by a '\n' character) with the fgets function and then supply
the line (or a part of that line if multiple numbers are represented in
each line) to a conversion function like strtol. If you use atoi be
aware that it produces undefined behaviour with certain values and does
not indicate failure. The functions strtol and strtoul are really much
more robust.
Also you could read the file character by character with a function like
getc and do the conversion to a int value yourself, but it's usually
better to use standardised functions unless you're learning or have
special requirements.
Please provide us with the code for your attempted solution and an exact
description of the format of your text file to help you further.