473,762 Members | 6,675 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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
13 10447
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)(vo id *));

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_FAILU RE);
}
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_FAILU RE);
}
puts("File is open for reading.");
puts("Reading file into a linked list...");
while ((rc = get_line(&buff, &size, fp)) 0) {
tail = list_append(&he ad, 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_FAILU RE);
}
puts("File is open for writing.");
puts("Overwriti ng 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_FAILU RE);
}
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(*linept r, 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)(vo id *))
{
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.de ha 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:

222222222222222 222222222222222 222222222222222 2222222222222

Jun 27 '08 #12
"rio" <a@b.cwrites:
"Jens Thoms Toerring" <jt@toerring.de ha 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:

222222222222222 222222222222222 222222222222222 2222222222222
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_Keit h) 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:

22222222222222 222222222222222 222222222222222 22222222222222

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(ignorebl ks(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(unsigne d 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
2375
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
23775
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 line into string just takes to long. When I Import the file with access manually goes fast. But how to use this fromout a C# programme who has done this before and who can give met some answers
4
1988
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 files are located on drive C: in directory starting with InetPub/myapplication/directrory/files . Thing is,when the website is running, the application path is c:\windows\system32. I can manipulate the path to get this to work for now. Thing is,...
2
1545
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 I could read a file on the clients disk ? And another question I am curious about how hard is it to export/import mails to outlook if it possible ? Thanx in advance guys..
3
2279
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
2265
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 the server where the text file is sitting. Is there any way my web application can be given access rights to read the text file? At the moment we copy the text file to the web server where it can be read by the web application. We have it...
6
248991
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 System; using System.IO; using System.Diagnostics;
2
1493
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 nullException error is occur so anybody help me how to read a text file with the content "N/A" as soon as possible...........
3
1589
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, What is the best method to read into database. In Oracle, I know it has sql loader. As to SQL Server, What should be? Do I need to write the program to read each characters and line by line? Thanks,
2
3949
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 server that is not running IIS. I created a share on folder containing the text file on the second server and made it available to the Everyone Group. The asp program, which works when the file is local, doesn't work when I modify the...
0
9554
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9377
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9925
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9811
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6640
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5266
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3509
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2788
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.