473,396 Members | 1,865 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

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 10353
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Jongmin | last post by:
Hi Everybody, I have to read text files which resides in cab file. How can I read the text file by C#? Help me!!! thanks, Jongmin
6
by: G.Esmeijer | last post by:
Friends, I would like to read a text file (fixed length formaated) really fast and store the data into an Access database (2003). Using the streamreader and reading line by line, separating the...
4
by: who be dat? | last post by:
I feel stupid for asking this but I can't figure this out. I've got some text files I want my website to read. The text files are located in a subdirectory of my application. Physically, the...
2
by: Johan Wendelstam | last post by:
Hi I am trying to let the users select a txt file on their drive and then import all the text in it to a textbox ? I have figured out how to access a file on the server and import it but not how...
3
by: ad | last post by:
I have a text file in the directory of my web application. How can I read this text file into a string vaiable?
5
by: jannordgreen | last post by:
I use windows 2000 and Visual Studio 2003. I have a vbnet web application on our intranet that needs to read a text file that sits on a different server. The general user does not have access to...
6
Atran
by: Atran | last post by:
Hello: In this article: You will learn to Write or Read A Text File. Let's Begin: First Create a new project (ConsoleApp or WinApp). And Make sure your program uses these namespaces: using...
2
by: arulforum | last post by:
Actually i want to read Eventlog viewer Security log file using C#, in that log file some usernames value are found like N/A so when i read this file all are working fine except n/a when i read N/A...
3
by: Raymond Chiu | last post by:
Dear all, Now I have the simple task to read text file line by line into database (SQL Server 2000). If the text file is divided into different fields according to the number of characters,...
2
by: Scottie Boy | last post by:
Ok, I'm brand new to IIS and asp. (My experience is with apache on Solaris but we have gotten rid of that system.) I need to readin a text file with asp that is on the C: drive of another Windows...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.