473,729 Members | 2,340 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

fscanf issues, please help.

I can't seem to get this function to work correctly. I'm wondering
if anyone could help me out with this.

So I'm using the fscanf function to read the input stream and store
each string in the appropriate variables.

Here's what I'm reading from another file:

"# Number of power catergories: 9"

I store each string between a whitespace into a variable. When I print
out all those variables, I get randomness. Some of the outputs are as
follows:

"# Numbof of powecate9 cate9 134518740"

The code is displayed below:
input_file = fopen("output_H IER.txt", "r");

output_file = fopen( "blah.txt", "w" );

result = fscanf(input_fi le,"%s %s %s %s %s %s", &dummy[0], &dummy[1],
&dummy[2], &dummy[3], &dummy[4], &dummy[5]);

fprintf(output_ file,"%s %s %s %s %s %i\n", &dummy[0], &dummy[1],
&dummy[2], &dummy[3], &dummy[4], &dummy[5]);

Please assume that all the variables have been declared already. This
is just for testing purposes. But it doesn't seem to work correctly.
Any help would be much appreciated.

Nov 17 '06 #1
9 3226

quyvle wrote:
I can't seem to get this function to work correctly. I'm wondering
if anyone could help me out with this.

So I'm using the fscanf function to read the input stream and store
each string in the appropriate variables.

Here's what I'm reading from another file:

"# Number of power catergories: 9"

I store each string between a whitespace into a variable. When I print
out all those variables, I get randomness. Some of the outputs are as
follows:

"# Numbof of powecate9 cate9 134518740"

The code is displayed below:
input_file = fopen("output_H IER.txt", "r");

output_file = fopen( "blah.txt", "w" );

result = fscanf(input_fi le,"%s %s %s %s %s %s", &dummy[0], &dummy[1],
&dummy[2], &dummy[3], &dummy[4], &dummy[5]);

fprintf(output_ file,"%s %s %s %s %s %i\n", &dummy[0], &dummy[1],
&dummy[2], &dummy[3], &dummy[4], &dummy[5]);

Please assume that all the variables have been declared already.
Why should we do that? If we don't know clearly what you are passing to
fscanf, how can we be sure what's going on.

My initial guess was that you've declared something like this:-

char *dummy[6];

And you're passing the addresses of the uninitialised pointers to
fscanf(), but what do I know?

YEP - that's it. On a 32-bit machine, each of those pointers could hold
up to 4-bytes, which is what the output suggests...

The &s are incorrect, by passing them you are giving fscanf() and
fprintf() the address of a char pointer but telling them that it is the
address of an array of characters..

When you use a "%s" specifier to fscanf, you must provide the address
of a big enough character array to contain what fscanf finds...

In addition you have a mismatch in your format specifiers - you (try
to) read the "9" into a string, but try to output it as an integer...

Nov 17 '06 #2
"quyvle" <qu****@gmail.c omwrites:
I can't seem to get this function to work correctly. I'm wondering
if anyone could help me out with this.

So I'm using the fscanf function to read the input stream and store
each string in the appropriate variables.

Here's what I'm reading from another file:

"# Number of power catergories: 9"

I store each string between a whitespace into a variable. When I print
out all those variables, I get randomness. Some of the outputs are as
follows:

"# Numbof of powecate9 cate9 134518740"

The code is displayed below:
input_file = fopen("output_H IER.txt", "r");

output_file = fopen( "blah.txt", "w" );

result = fscanf(input_fi le,"%s %s %s %s %s %s", &dummy[0], &dummy[1],
&dummy[2], &dummy[3], &dummy[4], &dummy[5]);

fprintf(output_ file,"%s %s %s %s %s %i\n", &dummy[0], &dummy[1],
&dummy[2], &dummy[3], &dummy[4], &dummy[5]);

Please assume that all the variables have been declared already.
There is some evidence from the sample output you show that this
assumption would be wrong! Prove me wrong by posting a complete
example that exhibits the problem.

There is no declaration that I can think of that will allow &dummy[5]
to be supplied as the target for an fscanf %s format and as the source
for an fprintf %i format! (You probably want %d as the last fscanf
format and a suitably declared variable to receive the number.)

--
Ben.
Nov 17 '06 #3
I did declare it as a char *dummy[6].

I guess, I would have to allocate memory to the pointers then.

This is what I get for learning perl first.

Nov 17 '06 #4
Could someone show me how to get this accomplished? I'm somewhat
confused. I thought you were suppose to make an array of pointers and
those pointers point to strings of whatever length.

Nov 17 '06 #5

quyvle wrote:
Could someone show me how to get this accomplished? I'm somewhat
confused. I thought you were suppose to make an array of pointers and
those pointers point to strings of whatever length.
n/m I guess I am going to use a double array of char type. I'm
wondering how would you initialize a pointer in an array of pointers?

char *dummy[10]

dummy = (char*)calloc(1 0, sizeof(char));

is that it?

Nov 17 '06 #6
quyvle wrote:
>
Could someone show me how to get this accomplished? I'm somewhat
confused. I thought you were suppose to make an array of pointers
and those pointers point to strings of whatever length.
How to get what accomplished? Your post makes no sense whatsoever.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

Nov 17 '06 #7
quyvle <qu****@gmail.c omwrote:
Could someone show me how to get this accomplished? I'm somewhat
confused. I thought you were suppose to make an array of pointers and
those pointers point to strings of whatever length.
Definitely *no*. An array of pointers is an array of pointer,
nothing more. Once you have defined an array of pointers the
pointers don't point to anything you would be able to use,
they pont to some random places in memory. Before you can use
them in any way _you_ have to make them point to memory you own
(obtained by either defining a variable or array or calling a
function like malloc()). And, moreover, there are no strings of
"whatever" length in C. If you want a string of a _certain_
length you must ask for it, either by defining an array of chars
or by calling malloc() (if you use malloc() and you're lucky,
the system will give it to you). Once you got it you can use
its exact length, but not a single character more - if you get
it wrong you're in for bad surprises: it could work anyway (but
suddenly fail if you update your compiler or tray it on a different
system), the program could crash in some unforseeable place or it
could look like it works but the results of the program are wrong.

If you come from a Perl background then you have to get rid of
quite a number of assumptions. Perl (and other higher-level
languages) frees you from the burden of thinking very carefully
about where memory comes from - if you have a variable, memory is
suddenly there when you need it. Moreover, if you have an array,
then you can put all kinds of things into it - one element could
be an integer, the next one a string, followed by a hash etc.,
but that's also something you won't get in C. To do this Perl
does a lot of "magic" in the background (that's one reason why
Perl scripts tend to be slower than C programs). But in C nothing
of this is happening, you must do it all by yourself. And you must
be careful to get it right, otherwise all bets are off.

If you only need an array of NUM_STRINGS strings of all the same
length STRING_LENGTH, then something like

char my_string[ NUM_STRINGS ][ STRING_LENGTH ];

is the definition you need. But if you e.g. don't know how long
the different strings are going to be then you would first need
an array of char pointers

char *my_string[ NUM_STRINGS ];

and, once you know how long the individual strings are going to be,
call malloc() for each of the elements of this array to obtain
enough memory. I.e. if you know that the first of the strings is
going to need 99 chars you would call

if ( ( my_string[ 0 ] = malloc( 100 ) ) == NULL ) {
fprintf( stderr, "malloc() failure\n" );
exit( EXIT_FAILURE );
}

If everything goes well you end up with the first pointer of the
array pointing to enough memory for a string consisting of 99
characters (the extra one is going to be needed for the trailing
'\0' character that indicates the end of the string). Since you
can never be sure that everything goes well, you have to check
every time you request memory.

[Hint: never cast the return value of malloc(). If you do all
you get out of it is keeping the compiler from warning you if
you forgot to include <stdlib.hand, if you did it, creating
a bug that can be extremely hard to find since then the return
value of malloc() is automatically converted to an int before
the resulting integer value is re-converted via the cast to a
pointer, which unfortunately works without a problem on a set
of (popular) machines, but fails badly on others.]

If you don't know how long the string you will have to read is
going to be you're in for even some more work. You have to come
up with a method to determine what's going to be needed, then
allocate memory and only then get hold of the string and put it
where you want it. That's why a function like fscanf() is rather
difficult to use with string input (and also other user input!) -
you hardly ever know an upper bound on the length of the string.
Thus you typically resort to using fgets() where you can read in
a certain number of characters, test if you got no more than fits
into the memory you have (in that case you're done) or the memory
got filled up but there's more, so you need to allocate more memory
and continue to read.

All these things are done in Perl automagically, so you don't got
to worry about it. But something in the innards of Perl is exactly
doing it for you (Perl is implemented in C) - and if you write in
C you have to take care of it all by yourself. All that may look
tedious (it often is:-) or even scary, but once you get the hang
of it it's not _that_ complicated.

Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\______________ ____________ http://toerring.de
Nov 18 '06 #8
On 17 Nov 2006 12:25:19 -0800, "quyvle" <qu****@gmail.c omwrote:
>
quyvle wrote:
>Could someone show me how to get this accomplished? I'm somewhat
confused. I thought you were suppose to make an array of pointers and
those pointers point to strings of whatever length.

n/m I guess I am going to use a double array of char type. I'm
wondering how would you initialize a pointer in an array of pointers?

char *dummy[10]

dummy = (char*)calloc(1 0, sizeof(char));

is that it?
Did you try it? Did your compiler complain that dummy could not
appear on the left of the assignment operator? No array object can. C
does not support assigning to an array.

You declare dummy as an array of 10 pointer to char. dummy is an
aggregate object. (For an array, the objects that make up the
aggregate are called elements.) In the case of dummy, it consists of
10 scalar objects. Each of these scalar objects is a pointer. The
value of each is independent of the others. In particular, assigning
a value to one has no affect on the value of any other.

What you need is code that assigns a value to each of the elements.
One method is
dummy[0] = /* a legal address */;
dummy[1] = /* another (possibly the same) legal address */;
...
dummy[9] = ...
Another method is
for (i = 0; i < 10; i++)
{
dummy[i] = calloc(10, sizeof *dummy[i]);
/* most would use malloc here but I tried to be consistent
with the example you posted */
if (dummy[i] == NULL)
{ /* code to handle allocation failure */}
}

Note that you do not want to cast the return from calloc or any of its
cousins.
Remove del for email
Nov 20 '06 #9
quyvle wrote:
I can't seem to get this function to work correctly. I'm wondering
if anyone could help me out with this.
(fx:snippage)
Please assume that all the variables have been declared already. This
is just for testing purposes. But it doesn't seem to work correctly.
Any help would be much appreciated.
If you don't understand what's going wrong, you don't know what it's
safe not to tell us, and we can't use your context to support our reply.

--
Chris "VOOM? What means this VOOM?" Dollin
"- born in the lab under strict supervision -", - Magenta, /Genetesis/

Nov 20 '06 #10

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

Similar topics

22
5030
by: John Phung | last post by:
Is there a fscanf equivalent for c++? Here's what I'm talking about: unsigned int NextAddress(ifstream& AddressFile) { unsigned int next_address; -->How do I rewrite the fscanf listed below using ifstream? -->fscanf(AddressFile, "%x", next_address); if(AddressFile.eof()) { return 0;
2
2829
by: Blankdraw | last post by:
.... somewhere, a newbie is dying ... Is there anybody out there who can help me get the right input for the following segment? I am trying to read entire records of 5 (2-digit) integers at a time. It would be best to read the integers into their own 5 respective variables. I thought I had it. I've redone my program so many different ways I am coming to the same conclusion I did when I tried to do it several years ago: that it cannot...
3
6733
by: Benedicte | last post by:
Hi, I'm getting some problems when using fscanf to read a file. This is a piece of the program code: main () { /*** Variable declaration ***/ FILE *vpfile; /*** Data file ***/
2
401
by: Petros Makris | last post by:
(please forgive me i don't know how to find older messages if this is already answered) I am trying to understand why fscanf( fp, "%s=%s\n", str1, str2); doesn't work when I am trying to read from a text file the following --------------------------------
5
424
by: learner | last post by:
I have datafiles like this: 0 1941 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.02 0.00 0.00 1 0 1941 0.00 0.03 0.00 0.03 0.04 0.02 0.00 0.00 0.00 0.00 2 0 1941 0.00 0.00 0.00 0.00 0.52 0.00 0.00 0.17 1.07 0.09 3 0 1941 0.04 0.00 0.00 0.00 0.00 0.62 0.00 0.01 0.00 0.00 4 0 1941 0.00 0.02 0.00 0.00 0.00 0.22 0.00 0.00 0.00 0.16 5 0 1941 0.00 0.00 0.00 0.00 0.09 0.04 0.00 0.00 0.00 0.00 6 0 1941 0.00...
5
1900
by: gb | last post by:
Hi, I have a small program which opens a file (Whose content is a mac address in the form xx:xx:xx:xx:xx:xx) and uses fscanf() to get individual bytes into an array which is defined as "unsigned char macaddress". The strange thing is that it prints zeroes on MIPS processor where as it works correctly on x86 systems. Appreciate if some body could help to understand the fscanf() behavior. Here is the code I am using:
13
510
by: PeterOut | last post by:
I am using MS Visual C++ 6.0 on Windows XP 5.1 (SP2). I am not sure if this is a C, C++ or MS issue but fscanf has been randomly hanging on me. I make the call hundreds, if not thousands, of times but it hangs in different places with the same data. The offending code follows. ReadFile(char *csFileName) { float fFloat1, fFloat2;
10
3665
by: rsk | last post by:
Hi Friends, I have written a code which suppose to read all the numbers from a hex file,But to my surprise the code is skiping every alternate value.Don't know why? Can you please help me in solving this problem. The code is as follows;
3
1834
by: Ranioo | last post by:
Hello everybody: i'm a new member in this site and i realy have a problem with c++. ok my problem is : i want to read text from a file and the text contains characters and decimal and hexadecimal using fscanf but when i debug (run the program) i only get smiley faces...??? but when i used getc() it worked ok!!! but the homework is with using fscanf()?????? this my program and i hope someone responds very fast i'm running out of...
0
8921
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
9427
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
9284
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
9202
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
9148
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
6022
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
4528
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
4796
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2683
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.