469,953 Members | 2,392 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,953 developers. It's quick & easy.

how to read integers from a text file

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.
Jun 27 '08 #1
13 9703
rohit ha scritto:
I tried the function fscanf but by that I am able to read
only the first integer of the text file.
Place each integer in a line and popolate an array v[] with these
values. Could be as follows:

/* ... */

#define DIM 100 /* max 100 integers */

int v[DIM];

/* 'n' is the number of integers (lines) max DIM values */
/* It is specified in the first line */
/* fpin is the pointer to FILE */

for (j=0;j<n;j++)
{
if(fscanf(fpin, "%d\n", &v[j])!=1)
{
fprintf(stderr, "\nData corrupted");
return 1;
}
}

/* ... */
Jun 27 '08 #2
nembo kid <nembo@kidwrote:
rohit ha scritto:
I tried the function fscanf but by that I am able to read
only the first integer of the text file.
Place each integer in a line and popolate an array v[] with these
For fscanf() to work they don't have to be on separate lines.
fscanf() skips all white-space characters, i.e. spaces, tabs
and line end characters (or character combinations) etc.
values. Could be as follows:
/* ... */
#define DIM 100 /* max 100 integers */
int v[DIM];
/* 'n' is the number of integers (lines) max DIM values */
/* It is specified in the first line */
/* fpin is the pointer to FILE */
for (j=0;j<n;j++)
{
if(fscanf(fpin, "%d\n", &v[j])!=1)
{
fprintf(stderr, "\nData corrupted");
return 1;
}
}
Or, if you don't know how many integers there are in the file
(but also assuming that you know an upper limit 'DIM'):

#include <stdio.h>
#include <stdlib.h>

(...)

int count = 0;

(...)

while ( count < DIM && fscanf( fpin, "%d", v + count ) == 1 )
count++;

if ( ferror( fpin ) )
{
fprintf( stderr, "Read failure\n" );
exit( EXIT_FAILURE );
}

But it would be much better if you would show what you did
try yourself. In that case you would get an explanation of
why it didn't work and how to improve it. And that, in the
long run, will help you much more than just blindly using
other peoples code...
Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\__________________________ http://toerring.de
Jun 27 '08 #3
In article <3d**********************************@x19g2000prg. googlegroups.com>,
rohit <ro**********@gmail.comwrote:
>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.
<OT>I think you'll find this a lot easier to do it in AWK, than
bothering with C.

It sounds to me like what you are doing is a perfect fit for AWK.

Jun 27 '08 #4
On Sun, 1 Jun 2008 03:56:06 -0700 (PDT), rohit
<ro**********@gmail.comwrote:
>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.

Remove del for email
Jun 27 '08 #5
rohit wrote:
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.

Jun 27 '08 #6
On Sun, 1 Jun 2008 03:56:06 -0700 (PDT), rohit
<ro**********@gmail.comwrote:
>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.
Show your code.
Remove del for email
Jun 27 '08 #7
If the integers are stored as text in the given file, you can read
them in a buffer and parse the individual items using sscanf. If you
want to directly go for fread, then it more or less requires that the
data be written in the same format by fwrite or something ( owing to
the endian-ness and the variable size of data types ).

No one likes to write code to explain something to someone. It would
be far easier for everyone if you post your own code snippets.
Jun 27 '08 #8
rahul wrote:

<snip>
No one likes to write code to explain something to someone.
I think pete might disagree with you there. :-)

<snip>

Jun 27 '08 #9
santosh wrote:
rahul wrote:

<snip>
>No one likes to write code to explain something to someone.

I think pete might disagree with you there. :-)

<snip>

/* BEGIN new.c */

#include <stdio.h>

int main(void)
{
const int one = 1;
char array[7] = {0};

if (one == sizeof *(one ? NULL : array)) {
puts("You are correct!");
} else {
puts("I disagree.");
}
return 0;
}

/* END new.c */
--
pete
Jun 27 '08 #10
rohit wrote:
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.
If you have any questions about the code,
I'll answer them as best as I can.
/* BEGIN new.c output */

File is open for writing.
File values:
150, 140, 242, 72, 14
File is closed.
Array values:
3, 1, 3, 1, 3
File is open for reading.
Reading file into a linked list...
File is closed.
File is open for writing.
Overwriting file with product of list and array values...
List is freed.
File is closed.
File is open for reading.
File values:
450, 140, 726, 72, 42
Line reading buffer is freed.
File is closed.
File is removed.

/* END new.c output */


/* BEGIN new.c */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>

#define N 5
#define NMEMB(A) (sizeof (A) / sizeof *(A))
#define LU_RAND_SEED 123456789LU
#define LU_RAND(S) ((S) * 69069LU + 362437 & 0XFFFFFFFF)

struct list_node {
struct list_node *next;
void *data;
};

typedef struct list_node list_type;

int get_line(char **lineptr, size_t *n, FILE *stream);
list_type *list_append
(list_type **head, list_type *tail, void *data, size_t size);
void list_free(list_type *node, void (*free_data)(void *));

int main(void)
{
int rc;
size_t index;
FILE *fp;
char fn[L_tmpnam];
long unsigned array[N];
long unsigned seed = LU_RAND_SEED;
char *buff = NULL;
size_t size = 0;
list_type *head = NULL;
list_type *tail = NULL;

puts("/* BEGIN new.c output */\n");
tmpnam(fn);
fp = fopen(fn, "w");
if (fp == NULL) {
fputs("fopen(fn), \"w\") == NULL\n", stderr);
exit(EXIT_FAILURE);
}
puts("File is open for writing.");
puts("File values:");
for (index = 0; index != NMEMB(array); ++index) {
seed = LU_RAND(seed) & 0xff;
fprintf( fp, "%lu\n", seed);
fprintf(stdout, "%4lu,", seed);
seed = LU_RAND(seed);
array[index] = seed & 0x3;
}
puts("\b ");
fclose(fp);
puts("File is closed.");
puts("Array values:");
for (index = 0; index != NMEMB(array); ++index) {
fprintf(stdout, "%4lu,", array[index]);
}
puts("\b ");
fp = fopen(fn, "r");
if (fp == NULL) {
fputs("fopen(fn, \"r\") == NULL\n", stderr);
exit(EXIT_FAILURE);
}
puts("File is open for reading.");
puts("Reading file into a linked list...");
while ((rc = get_line(&buff, &size, fp)) 0) {
tail = list_append(&head, tail, buff, rc);
if (tail == NULL) {
fputs("tail == NULL\n", stderr);
break;
}
}
fclose(fp);
puts("File is closed.");
fp = fopen(fn, "w");
if (fp == NULL) {
fputs("fopen(fn), \"w\") == NULL\n", stderr);
exit(EXIT_FAILURE);
}
puts("File is open for writing.");
puts("Overwriting file with product of list and array values...");
for (tail = head, index = 0; index != NMEMB(array); ++index) {
seed = strtoul(tail -data, NULL, 10);
fprintf(fp, "%lu\n", array[index] * seed);
tail = tail -next;
if (tail == NULL) {
break;
}
}
list_free(head, free);
puts("List is freed.");
fclose(fp);
puts("File is closed.");
fp = fopen(fn, "r");
if (fp == NULL) {
fputs("fopen(fn, \"r\") == NULL\n", stderr);
exit(EXIT_FAILURE);
}
puts("File is open for reading.");
puts("File values:");
while ((rc = get_line(&buff, &size, fp)) 0) {
fprintf(stdout, "%4s,", buff);
}
puts("\b ");
free(buff);
buff = NULL;
size = 0;
puts("Line reading buffer is freed.");
fclose(fp);
puts("File is closed.");
remove(fn);
puts("File is removed.");
puts("\n/* END new.c output */");
return 0;
}

int get_line(char **lineptr, size_t *n, FILE *stream)
{
int rc;
void *p;
size_t count;

count = 0;
while ((rc = getc(stream)) != EOF
|| !feof(stream) && !ferror(stream))
{
++count;
if (count == (size_t)-2) {
if (rc != '\n') {
(*lineptr)[count] = '\0';
(*lineptr)[count - 1] = (char)rc;
} else {
(*lineptr)[count - 1] = '\0';
}
break;
}
if (count + 2 *n) {
p = realloc(*lineptr, count + 2);
if (p == NULL) {
if (*n count) {
if (rc != '\n') {
(*lineptr)[count] = '\0';
(*lineptr)[count - 1] = (char)rc;
} else {
(*lineptr)[count - 1] = '\0';
}
} else {
if (*n != 0) {
**lineptr = '\0';
}
ungetc(rc, stream);
}
count = 0;
break;
}
*lineptr = p;
*n = count + 2;
}
if (rc != '\n') {
(*lineptr)[count - 1] = (char)rc;
} else {
(*lineptr)[count - 1] = '\0';
break;
}
}
if (rc != EOF || !feof(stream) && !ferror(stream)) {
rc = INT_MAX count ? count : INT_MAX;
} else {
if (*n count) {
(*lineptr)[count] = '\0';
}
}
return rc;
}

list_type *list_append
(list_type **head, list_type *tail, void *data, size_t size)
{
list_type *node;

node = malloc(sizeof *node);
if (node != NULL) {
node -next = NULL;
node -data = malloc(size);
if (node -data != NULL) {
memcpy(node -data, data, size);
if (*head != NULL) {
tail -next = node;
} else {
*head = node;
}
} else {
free(node);
node = NULL;
}
}
return node;
}

void list_free(list_type *node, void (*free_data)(void *))
{
list_type *next_node;

while (node != NULL) {
next_node = node -next;
free_data(node -data);
free(node);
node = next_node;
}
}

/* END new.c */

--
pete
Jun 27 '08 #11
rio

"Jens Thoms Toerring" <jt@toerring.deha scritto nel messaggio
news:6a*************@mid.uni-berlin.de...
nembo kid <nembo@kidwrote:
>rohit ha scritto:
I tried the function fscanf but by that I am able to read
only the first integer of the text file.
>Place each integer in a line and popolate an array v[] with these

For fscanf() to work they don't have to be on separate lines.
fscanf() skips all white-space characters, i.e. spaces, tabs
and line end characters (or character combinations) etc.
>values. Could be as follows:
but fscanf can catch the overflow or a wrong input?
something like:

22222222222222222222222222222222222222222222222222 22222222

Jun 27 '08 #12
"rio" <a@b.cwrites:
"Jens Thoms Toerring" <jt@toerring.deha scritto nel messaggio
news:6a*************@mid.uni-berlin.de...
>nembo kid <nembo@kidwrote:
>>rohit ha scritto:
I tried the function fscanf but by that I am able to read
only the first integer of the text file.
>>Place each integer in a line and popolate an array v[] with these

For fscanf() to work they don't have to be on separate lines.
fscanf() skips all white-space characters, i.e. spaces, tabs
and line end characters (or character combinations) etc.
>>values. Could be as follows:

but fscanf can catch the overflow or a wrong input?
something like:

22222222222222222222222222222222222222222222222222 22222222
No. C99 7.19.6.2p10:

If this object does not have an appropriate type, or if the result
of the conversion cannot be represented in the object, the
behavior is undefined.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jun 27 '08 #13
Keith Thompson wrote:
"rio" <a@b.cwrites:
.... snip ...
>
>but fscanf can catch the overflow or a wrong input?
something like:

2222222222222222222222222222222222222222222222222 222222222

No. C99 7.19.6.2p10:

If this object does not have an appropriate type, or if the
result of the conversion cannot be represented in the object,
the behavior is undefined.
The following code can easily be modified to received longs, or
long longs, if desired. Note that no buffers are required, the
reading is performed directly from the file.

/* -------------------------------------------------------------
* Skip to non-blank on f, and return that char. or EOF The next
* char that getc(f) will return is unknown. Local use only.
*/
static int ignoreblks(FILE *f)
{
int ch;

do {
ch = getc(f);
} while ((' ' == ch) || ('\t' == ch));
/* while (isblank(ch)); */ /* for C99 */
return ch;
} /* ignoreblks */

/*--------------------------------------------------------------
* Skip all blanks on f. At completion getc(f) will return
* a non-blank character, which may be \n or EOF
*
* Skipblks returns the char that getc will next return, or EOF.
*/
int skipblks(FILE *f)
{
return ungetc(ignoreblks(f), f);
} /* skipblks */

/*--------------------------------------------------------------
* Skip all whitespace on f, including \n, \f, \v, \r. At
* completion getc(f) will return a non-blank character, which
* may be EOF
*
* Skipwhite returns the char that getc will next return, or EOF.
*/
int skipwhite(FILE *f)
{
int ch;

do {
ch = getc(f);
} while (isspace(ch));
return ungetc(ch, f);
} /* skipwhite */

/*--------------------------------------------------------------
* Read an unsigned value. Signal error for overflow or no
* valid number found. Returns 1 for error, 0 for noerror, EOF
* for EOF encountered before parsing a value.
*
* Skip all leading blanks on f. At completion getc(f) will
* return the character terminating the number, which may be \n
* or EOF among others. Barring EOF it will NOT be a digit. The
* combination of error, 0 result, and the next getc returning
* \n indicates that no numerical value was found on the line.
*
* If the user wants to skip all leading white space including
* \n, \f, \v, \r, he should first call "skipwhite(f);"
*
* Peculiarity: This specifically forbids a leading '+' or '-'.
*/
int readxwd(unsigned int *wd, FILE *f)
{
unsigned int value, digit;
int status;
int ch;

#define UWARNLVL (UINT_MAX / 10U)
#define UWARNDIG (UINT_MAX - UWARNLVL * 10U)

value = 0; /* default */
status = 1; /* default error */

ch = ignoreblks(f);

if (EOF == ch) status = EOF;
else if (isdigit(ch)) status = 0; /* digit, no error */

while (isdigit(ch)) {
digit = ch - '0';
if ((value UWARNLVL) ||
((UWARNLVL == value) && (digit UWARNDIG))) {
status = 1; /* overflow */
value -= UWARNLVL;
}
value = 10 * value + digit;
ch = getc(f);
} /* while (ch is a digit) */

*wd = value;
ungetc(ch, f);
return status;
} /* readxwd */

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.
** Posted from http://www.teranews.com **
Jun 27 '08 #14

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

reply views Thread by Jongmin | last post: by
6 posts views Thread by G.Esmeijer | last post: by
4 posts views Thread by who be dat? | last post: by
2 posts views Thread by Johan Wendelstam | last post: by
3 posts views Thread by Raymond Chiu | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.