473,657 Members | 2,680 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 #1
13 10397
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************ *************** *******@x19g200 0prg.googlegrou ps.com>,
rohit <ro**********@g mail.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**********@g mail.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**********@g mail.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

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2370
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
23764
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
1973
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
1540
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
2273
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
2254
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
248944
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
1478
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
1581
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
3945
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
8319
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,...
0
8837
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8739
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8512
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,...
1
6175
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5638
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
4171
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
4329
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2739
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.